gpt4 book ai didi

c# - 获取泛型类中的接口(interface)属性值

转载 作者:行者123 更新时间:2023-12-04 04:53:04 27 4
gpt4 key购买 nike

我有这个界面

public interface IMyInterface
{
IEnumerable<MyParamInfo> Params { get; }
}
在哪里
MyParamInfo 是
public class MyParamInfo 
{
public MyParamInfo (string name)
{
Name= name;
}
public string Name { get; private set; }
}

这节课
public class MyClass:IMyInterface
{
//properties
....
public IEnumerable<MyParamInfo> Params
{
get
{
return new List<MyParamInfo> { new MyParamInfo("Param1")};
}
}
}
和这个表格
public partial class MyForm<T> : Form where T:Class,IMyInterface
{
...
}
使用此代码
MyForm<MyClass> frm = new MyForm<MyClass>();
如何访问 frm 对象中 MyClass 的 Params 属性?

最佳答案

如果您还需要 T MyForm 的类型参数有一个无参数的构造函数,你可以实例化 T 的实例然后随意使用interface属性。

关于MyForm的定义, 添加 new()通用约束

public partial class MyForm<T> : Form where T : Class, IMyInterface, new()

然后在 MyForm<T>的一些方法中, 您可以使用:
(new T()).Params;

您可以阅读 C# here 中关于类型参数的所有约束。 .

看起来您真正想要的是可以指定静态方法的接口(interface)(所谓的静态接口(interface))。 C# 中不存在这样的构造。

关于c# - 获取泛型类中的接口(interface)属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17139934/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com