A级
class A{
...
}
B级
class B:A{
...
}
C类
class C:A{
B[] bArray{get;set;}
}
我想检查 T 是否具有 S 属性类型,创建 S 实例并分配给该属性:
public Initial<T,S>() where T,S : A{
if(T.has(typeof(S))){
S s=new S();
T.s=s;
}
}
最佳答案
最好也是最简单的方法是使用接口(interface)实现此功能。
public interface IHasSome
{
SomeType BArray {get;set;}
}
class C:A, IHasSome
{
public SomeType BArray {get;set;}
}
然后您可以在通用方法中强制转换对象:
public T Initial<T,S>() where T : new() where S : SomeType, new()
{
T t = new T();
if (t is IHasSome)
{
((IHasSome)t).BArray = new S();
}
return t;
}
如果这不合适,您可以使用反射来检查属性并检查它们的类型。相应地设置变量。
关于c# - 检查 T 泛型类型是否具有 C# 中的属性 S(泛型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35196745/