2016-09-01 43 views
3

我需要使用属性的位置或任何其他类似的方式访问泛型类型的属性。按位置访问泛型类型的属性

例子:

class model 
{ 
    int intValue; 
    string stringValue; 

    public model(int a,string b){ 
    this.intValue = a; 
    this.stringValue= b; 
    } 
} 



public class baseClass<T> 
{ 
    public string value; 

    public void process(T param) 
    { 
     value = param.Getproperty[0].ToString(); 
    } 

} 

public class derivedClass : baseClass<model> 
{ 
    Console.WriteLine("Converted value:" +process(new model(1,"test"))); 
    //Do something 
}  

我的基类,实际上是执行一些简单的常规任务通用库。

+1

“在运行时添加”?这是什么意思? –

+0

另外,你在找[Type.GetProperties](https://msdn.microsoft.com/en-us/library/aky14axb(v = vs.110).aspx)? –

+0

@ LasseV.Karlsen我认为他们令运行时间和编译时间混淆 – MikeT

回答

1

您需要定义一个通用的接口,目前接口设置为对象,所以,只要不是对象的成员无法访问,这与where关键字

这可以明确地用做做实际的接口

public interface IIndexedProperty 
{ 
    object Getproperty(int index); 
} 

public class model:IIndexedProperty 
{ 
    int intValue; 
    string stringValue; 
    public object Getproperty(int index) 
    { 
     //select property by index 
    } 
} 

public class baseClass<T> 
    where T:IIndexedProperty 
{ 
    public T item; 
    item.Getproperty(0); // access intValue 
    item.Getproperty(1); // access stringValue 
} 

另一种选择是使用模型作为您的接口

public class model 
{ 
    int intValue; 
    string stringValue; 
} 

public void baseClass<T> 
    where T:model 
{ 
    public T item; 

    item.intValue; // access intValue 
    item.stringValue; // access stringValue 
} 

最终的选择将是反射

typeof(T).GetProperties(); 
0

你可以实现一个property indexer

示例代码:

public class TestIndexer 
{ 
    public string x; 
    public int y; 
    public object this[int i] 
    { 
     get 
     { 
      switch (i) 
      { 
       case 1: 
        return y; 
       case 2: 
        return x; 
       default: 
        return ""; 
       // return the property you want based on index i 
      } 
     } 
    } 
} 

TestIndexer t = new TestIndexer(); 
t.y = 22; 
object indexValue = t[1]; //22 
+0

他们仍然无法访问索引器,除非他们用where子句键入泛型 – MikeT

1

我建议另一种方法?

如果你总是有2个propeteries

interface TwoProperties { 
    object GetProperty1(); 
    object GetProperty2(); 
} 

class Model : TwoProperties { 
    int intValue; 
    stringStringValue; 

    public override object GetProperty1() { 
    return intValue; 
    } 

    public override object GetProperty2() { 
    return stringValue; 
    } 
} 

然后用someModel.GetProperty1()例如。

如果你有一个未知数量的属性:

interface SomeProperties { 
    object[] GetProperties(); 
} 

class Model : SomeProperties { 
    int intValue; 
    stringStringValue; 

    public override object[] GetProperties() { 
    return new object[] { intValue, stringValue }; 
    } 
} 

然后用someModel.GetProperties()[0],例如。