首页 新闻 会员 周边

C#反射获取特性值的问题

0
悬赏园豆:30 [已关闭问题] 关闭于 2017-05-09 08:01

这是我通过反射获取特性输出[System.ComponentModel.DataAnnotations.DisplayAttribute(Name = "key")]

我现在已经通过反射获取到特性了,就是在Invoke方法里不知道填实例的第一个参数

1             var result = attrs.FirstOrDefault(a => a.AttributeType == typeof(Displa         yAttribute));
2             Console.WriteLine(result);
3             Console.WriteLine(result.AttributeType.GetMethod("GetName").Invoke(????,null));

我在里边填result肯定是不对的,系统会抛异常,我如果new DisplayAttribute(),就不会抛异常,但是这样肯定是不对的。就是卡在这里不知道这里怎么填?

问题补充:

不要给我说截取字符串的方法

Bluto的主页 Bluto | 菜鸟二级 | 园豆:317
提问于:2017-05-08 21:30
< >
分享
所有回答(3)
0

为什么你还要通过GetMethod方式去invoke?你这里拿出来的result就是包含这个attribute对象(字段,属性等)的DisplayAttribute的实例啊,你直接强转为DisplayAttribute就可以拿里面的信息了。

Daniel Cai | 园豆:10424 (专家六级) | 2017-05-08 22:08

强转肯定是不行的,在反射里边全是类型,怎么转化为实例

支持(0) 反对(0) Bluto | 园豆:317 (菜鸟二级) | 2017-05-09 07:45
 var result = attrs.FirstOrDefault(a => a.AttributeType == typeof(DisplayAttribute));
            //下边这行是重点代码
            var mykey = result.NamedArguments[0].TypedValue.Value;
            Console.WriteLine(result);
            Console.WriteLine(mykey);

通过这个解决了

支持(0) 反对(0) Bluto | 园豆:317 (菜鸟二级) | 2017-05-09 12:27
0

有一个getco开头的.获取自定义特性传入的参数的.

可以直接取到参数值.不用管对象.

吴瑞祥 | 园豆:29449 (高人七级) | 2017-05-08 22:47
0

可以参考如下代码:System.Reflection.Assembly assembly = cr.CompiledAssembly; Type[] types = assembly.GetTypes(); Type t = types[0]; object obj = Activator.CreateInstance(t); System.Reflection.MethodInfo mi = t.GetMethod(methodname); return mi.Invoke(obj, args);

式圣2012 | 园豆:196 (初学一级) | 2017-05-08 22:51

多谢你的提醒 

我是这样测试的

 var obj = Activator.CreateInstance(result.AttributeType);
            var result1 = result.AttributeType.GetMethod("GetName").Invoke(obj,null);
            Console.WriteLine(result1);

取的值是空

支持(0) 反对(0) Bluto | 园豆:317 (菜鸟二级) | 2017-05-09 07:51
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册