C# 获取泛型类中的接口属性值
我有这个接口C# 获取泛型类中的接口属性值,c#,generics,C#,Generics,我有这个接口 public interface IMyInterface { IEnumerable<MyParamInfo> Params { get; } } 也 这个班 public class MyClass:IMyInterface { //properties .... public IEnumerable<MyParamInfo> Params { get { ret
public interface IMyInterface
{
IEnumerable<MyParamInfo> Params { get; }
}
也
这个班
public class MyClass:IMyInterface
{
//properties
....
public IEnumerable<MyParamInfo> Params
{
get
{
return new List<MyParamInfo> { new MyParamInfo("Param1")};
}
}
}
公共类MyClass:IMyInterface
{
//性质
....
公共IEnumerable参数
{
得到
{
返回新列表{new MyParamInfo(“Param1”)};
}
}
}
这张表呢
public partial class MyForm<T> : Form where T:Class,IMyInterface
{
...
}
public分部类MyForm:Form,其中T:class,IMyInterface
{
...
}
使用此代码
MyForm<MyClass> frm = new MyForm<MyClass>();
MyForm frm=new MyForm();
如何访问frm对象中MyClass的Params属性?如果您还要求
MyForm
的T
type参数具有无参数构造函数,则可以实例化T
的实例,然后随意使用接口属性
在MyForm
的定义中,添加new()
通用约束
public partial class MyForm<T> : Form where T : Class, IMyInterface, new()
您可以阅读C#中关于类型参数的所有约束
看起来您真正想要的是可以指定静态方法的接口(所谓的静态接口)。C#中不存在这样的构造
MyClass
在这里适合什么?您的表单是否应该扩展MyClass
?在MyForm
中使用MyClass
?
public partial class MyForm<T> : Form where T : Class, IMyInterface, new()
(new T()).Params;