【问题标题】:Check T generic type has property S (generic) in c#检查 T 泛型类型在 C# 中具有属性 S(泛型)
【发布时间】:2016-05-13 19:30:07
【问题描述】:

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

【问题讨论】:

  • 如果 T 有多个 S 类型的属性怎么办?
  • 或者,说“哪里 T,S : C”。如果这就是方法的全部。
  • @Ralf 谢谢你的提醒,我没想到 :-(

标签: c# generics reflection properties typeof


【解决方案1】:

最好和最简单的做法是使用接口实现此功能。

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

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

【讨论】:

  • 我希望 Initial 方法返回 T 而不是 void。否则我看不出它有什么用...
  • @ZoharPeled 同意。 OP没有指定返回类型,所以我只插入了void
  • 是的,我只是对这个问题写评论,但他们发布了你的答案,所以我决定在这里发表评论。除此之外,我同意 - 接口是通往这里的道路。
【解决方案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);

【讨论】:

    猜你喜欢
    • 2012-07-04
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 2022-01-03
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 2013-11-22
    相关资源
    最近更新 更多