2016-02-04 87 views
0

类A检验T通用类型具有属性S(通用)在c#

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

如果T有多个S型属性,该怎么办? – Ralf

+0

或者,说“哪里T,S:C”。如果这就是所有的方法。 –

+0

@Ralf谢谢你的提醒,我没有想到:-( –

回答

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

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

+0

我期望Initial方法返回T而不是void,否则我看不出它会如何有用... –

+0

@ZoharPeled同意。OP没有指定返回类型,所以我只是插入了'void'。 –

+0

是的,我只是写了一个关于这个问题的评论,但他们发布了你的答案,所以我决定在这里发表评论。 ,我同意 - 接口是去这里的路。 –

0

我同意@PatrickHofman这种方式比较好,但如果你想somethig更通用,创建一个类的所有属性的新实例,你可以做,使用反射:

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); 
+0

非常感谢:-) –

相关问题