检查T泛型类型在c#中具有属性S(泛型)

时间:2016-02-04 09:07:52

标签: c# generics reflection properties typeof

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;
   }
}

2 个答案:

答案 0 :(得分:2)

最好和最简单的方法是使用界面实现此功能。

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;
}

如果不合适,您可以使用反射来检查属性并检查其类型。相应地设置变量。

答案 1 :(得分:2)

我同意@PatrickHofman这种方式更好,但是如果你想要更通用的东西为类型的所有属性创建一个新实例,你可以使用反射来做到这一点:

public T InitializeProperties<T, TProperty>(T instance = null) 
    where T : class, new()
    where TProperty : new()
{
    if (instance == null)
        instance = new T();

    var propertyType = typeof(TProperty);
    var propertyInfos = typeof(T).GetProperties().Where(p => p.PropertyType == propertyType);

    foreach(var propInfo in propertyInfos)
        propInfo.SetValue(instance, new TProperty());

    return instance;
}

然后:

// Creates a new instance of "C" where all its properties of the "B" type will be also instantiated
var cClass = InitializeProperties<C, B>();

// Creates also a new instance for all "cClass properties" of the "AnotherType" type
cClass = InitializeProperties<C, AnotherType>(cClass);
相关问题