首页 新闻 会员 周边

如何对泛型T的属性操作

0
悬赏园豆:50 [已解决问题] 解决于 2010-02-01 11:51

比如,我一个类中,用到了反省T

 

其中有一个 函数需要更改

T 的一个属性

比如

T t = new T();

t.name="adsasd";

 

我确定我传入的T会有name,但是怎么实现?

Dozer的主页 Dozer | 初学一级 | 园豆:30
提问于:2010-01-31 21:26
< >
分享
最佳答案
1

如果可以的话,使用接口,比如:

interface INamed{

        string Name{get;set;}

}

class MyGenaric<T> where T: INamed, new() {

    void Method(){

                      T t = new T();

                       t.Name = "something else";//这里也可以向楼上说的,使用 as 进行类型转换后赋值,而免去泛型定义时的接口申明。但这样“编译器”不能保证使用该类型的开发人员,其具体泛型实现了该接口。

                       ...........

    }

}

这种从我的眼光看要优雅一些。如果接口不能由你来设定,那么大概需要使用反射吧:

          T t = ...;

          Property name = t.GetType().GetProperty("Name");

          name.SetValue(t, "something else");

我的写法肯定不对,但大概应该是这么个过程。

==================================

本来我是二楼,因为园子脚本的问题,唉……

收获园豆:50
陛下 | 老鸟四级 |园豆:3938 | 2010-02-01 09:38
其他回答(3)
0

1,别用泛型,以一个结构体为参数,当然接口要包含你需要的“Name”

2,用is对T进行判断(最好也定义好含“Name”的接口)。

齐.net | 园豆:1421 (小虾三级) | 2010-01-31 21:51
0

对于编译器来说,其无法知道你这个泛型有什么属性,你需要定义一个接口,然后在使用时将 泛型转换为这个接口来使用。

比如 IName 接口保护一个Name属性

T t = new T();

((IName)t).Name = "adsasd";

eaglet | 园豆:17139 (专家六级) | 2010-02-01 06:44
0

写个封装的类.你看看.

代码
public class PropertyHelper<T>
{
private T entiy;
public PropertyHelper(T t)
{
entiy
= t;
BindingAttr
= BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance;
}
public BindingFlags BindingAttr { get; set; }

public T Entiy
{
get
{
return entiy;
}
}
public object this[string name]
{
get
{
return this[name, null];
}
set
{
this[name,null] = value;
}
}
public object this[string name,object[] index]
{
get
{
if (name == null)
throw new ArgumentNullException("name");
object obj = null;
try
{
PropertyInfo info
= entiy.GetType().GetProperty(name, BindingAttr);
obj
= info.GetValue(entiy, index);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
return obj;
}
set
{
if (name == null)
throw new ArgumentNullException("name");
try
{
PropertyInfo info
= entiy.GetType().GetProperty(name, BindingAttr);
info.SetValue(entiy,value,index);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
}
}

 

1. 你的就如下操作就OK.如果BOMG有个属性如Name.

PropertyHelper<BomG> bh = new PropertyHelper<BomG>(bomg);

string name = bh["Name"] as string;

2.string dec = "qazxswedc";

ProPertyHelper<string> dechelper = new PropertyHelper<string>(dec);

int leng = (int)dechelper["Length"] ;

主要是把原来用属性操作的变成只要记得相关的属性字符串就行.

天天不在 | 园豆:926 (小虾三级) | 2010-02-01 08:39
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册