简体   繁体   English

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

[英]Check T generic type has property S (generic) in c#

class A A级

class A{
...
}

class B B级

 class B:A{
    ...
 }

class C C级

 class C:A{
    B[] bArray{get;set;}
 }

I would like to check if T has a property type of S , create instance of S and assignment to that propery : 我想检查T是否具有S的属性类型,创建S的实例并分配给该属性:

public Initial<T,S>() where T,S : A{
   if(T.has(typeof(S))){
      S s=new S();
      T.s=s;
   }
}

The best and easiest thing to do is implement this functionality using an interface. 最好和最简单的方法是使用接口来实现此功能。

public interface IHasSome
{
    SomeType BArray {get;set;}
}

class C:A, IHasSome
{
    public SomeType BArray {get;set;}
}

Then you can cast the object in your generic method: 然后,您可以使用通用方法转换对象:

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

If that doesn't fit, you can use reflection to go over the properties and check their types. 如果不合适,则可以使用反射遍历属性并检查其类型。 Set the variable accordingly. 相应地设置变量。

I agree with @PatrickHofman that way is better, but if you want somethig more generic that creates a new instance for all properties of a type, you can do that using reflection: 我同意@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;
}

Then: 然后:

// 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM