【发布时间】:2011-01-05 18:01:11
【问题描述】:
第一个问题是,如何获取存储在变量中的对象的类型?通常我们会这样做:
Type t = typeof(ClassName); //if I know the class
但是,我该怎么说呢:
Type t = typeof(varClassName); //if the class name is stored in a variable
第二个问题,更广泛的情况是,我有一个 WCF 服务,其中包含一个 DataContract 类,比如“MyClass”,并且我已经为它定义了一个名为“MyAttribute”的自定义属性。有一种方法说“GetDataUsingDataContract”,其参数类型为 MyClass。现在在客户端,我调用 Web 服务。我使用 MethodInfo 和 ParameterInfo 类来获取相关方法的参数。但是如何访问实际上是类 Myclass 的方法参数的属性?这是我尝试过的代码:
MyService.Service1Client client = new MyService.Service1Client();
Type t = typeof(MyService.Service1Client);
MethodInfo members = t.GetMethod("GetDataUsingDataContract");
ParameterInfo[] parameters = members.GetParameters();
foreach (var parameter in parameters)
{
MemberInfo mi = parameter.ParameterType; //Not sure if this the way
object[] attributes;
attributes = mi.GetCustomAttributes(true);
}
上面的代码没有检索到自定义属性“MyAttribute”。我在同一个项目中定义的类中尝试了这个概念并且它有效。请帮忙!
【问题讨论】:
标签: wcf custom-attributes typeof