Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#访问泛型类T的属性_C#_Generics - Fatal编程技术网

C#访问泛型类T的属性

C#访问泛型类T的属性,c#,generics,C#,Generics,我需要访问泛型类T的属性 我在泛型类中有这个方法 public T calcuste(T obj) { calcaulte testobj= new calcaulte () var t = GetValue(obj); // get the type of class for example that is calcaulte class testobj.Id = obj.Id;// that is what I need to do accessi

我需要访问泛型类T的属性 我在泛型类中有这个方法

 public T calcuste(T obj)
 {
      calcaulte testobj= new calcaulte ()
      var t = GetValue(obj); // get the type of class for example that is calcaulte class 

      testobj.Id = obj.Id;// that is what I need to do accessing a  property of T obj 
 }
试试下面的代码

public T calcuste(T obj)
{
    calcaulte testobj= new calcaulte ();
    calcaulte obj_calcaulte  = obj as calcaulte;
    if(obj_calcaulte  != null)
    {
        testobj.Id = obj_calcaulte  .Id;   
    }

}   

您需要控制null,因为obj可能为null,或者可能属于不同的类。

可能有助于显示类定义,以便我们可以看到
T
实际上是什么。我猜您需要一个接口,或者您是否知道可以转换为该类型的类型,例如
((计算)obj).Id
如果Id是calculate类中的一个字段。此代码错误太多,令人困惑。为什么要定义一个var t,却从不使用它?很难弄清楚你想做什么,你的问题是什么。考虑使用类型限制:不需要什么。