GVKun编程网logo

c# – 如何通过反射获取基本方法的MethodInfo,而不是属性和事件?(c#通过反射获取属性的值)

38

如果您对c#–如何通过反射获取基本方法的MethodInfo,而不是属性和事件?感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于c#–如何通过反射获取基本方法的MethodI

如果您对c# – 如何通过反射获取基本方法的MethodInfo,而不是属性和事件?感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于c# – 如何通过反射获取基本方法的MethodInfo,而不是属性和事件?的详细内容,我们还将为您解答c#通过反射获取属性的值的相关问题,并且为您提供关于asp.net – 通过反射获取其getter具有可选值的属性的值、c# – 如何通过反射获取类及其父类的私有字段?、c# – 识别MethodInfo实例是否是属性访问器、C# 通过反射获取方法/类上的自定义特性的有价值信息。

本文目录一览:

c# – 如何通过反射获取基本方法的MethodInfo,而不是属性和事件?(c#通过反射获取属性的值)

c# – 如何通过反射获取基本方法的MethodInfo,而不是属性和事件?(c#通过反射获取属性的值)

参见英文答案 > How to list interface methods omitting property accessors 2个
我正在对一个物体进行一些反思性的审讯.代码列出了构造函数,属性和方法. getmethods()返回属性accessor / mutator方法和事件添加/删除方法.

我怎样才能得到基本的方法定义?

更新

.IsspecialName

是有效财产.谢谢,@汉斯.

解决方法

这篇文章 Filtering out auto-generated methods getter/setter/add/remove/.etc) returned by Type.GetMethods()的以下答案应该有效
typeof(MyType)
.getmethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
.Where(m => !m.IsspecialName)

asp.net – 通过反射获取其getter具有可选值的属性的值

asp.net – 通过反射获取其getter具有可选值的属性的值

我正在检索控件的几个属性.以下是我用于检索属性的方法(使用PropertyInfo类型的pinfo):

value = pinfo.GetValue(obj,nothing)

这很好,但现在我面临一个具有可选值的属性,并且我收到一条错误消息,告诉我参数的数量不正确.所以我改变了我的代码:

Dim index As Object() = {nothing}
value = pinfo.GetValue(obj,index)

此时,我没有收到任何错误消息,但此代码未检索到良好的值.它只有在我用属性访问器提供的默认值替换nothing时才有效…

但我事先并不知道这个默认值是多少!并且此代码位于一个函数中,该函数检索没有可选值的属性,因此我无法更改代码,尤其是对于一种情况或另一种情况.

任何的想法?我正在研究.NET 2.0

编辑:关于导致问题的案件的更精确

以下是导致问题的属性示例:

ReadOnly Property Foo(Optional ByVal Number As Integer = -1) As String
    Get
        If Number = -1 Then
            Return "Your number is the default number: " & Number
        Else
            Return "Your number is " & Number
        End If
    End Get
End Property

有了这种属性,上面的代码都没有检索到好的字符串.

我最好的猜测是尝试第一个代码用于一般目的,捕获相应的异常,然后动态检索参数的默认值(在这种情况下为Number)及其类型,以便我可以使用此默认值调用getValue.

那么,如何检索可选参数的默认值?

解决方法

这适用于可选参数:

ReadOnly Property Foo(Optional name As String = nothing) As String
    Get
        If name Is nothing Then
            Return "Hello World"
        Else
            Return "Hello " & name
        End If
    End Get
End Property


Dim pinfo As Reflection.PropertyInfo = Me.GetType().GetProperty("Foo")
Dim value As Object = pinfo.GetValue(Me,New Object() {"Tim"})  ' Hello Tim '
value = pinfo.GetValue(Me,New Object(){nothing})               ' Hello World '

编辑:根据你的评论,整数不起作用,我还不知道如何在属性中获取可选参数的默认值.如果您知道它可以轻松传递它,但是否则会发生以下情况(注意Int32.MinValue是默认值而不是0):

ReadOnly Property Foo(Optional age As Int32 = Int32.MinValue) As String
    Get
        If age = Int32.MinValue Then
            Return "I don't kNow how old i am"
        Else
            Return String.Format("I am {0} years old",age)
        End If
    End Get
End Property

Dim pinfo As Reflection.PropertyInfo = Me.GetType.GetProperty("Foo")
Dim value As Object = pinfo.GetValue(Me,New Object() {38})  ' I am 38 years old '
value = pinfo.GetValue(Me,New Object() {nothing})           ' I am 0 years old '
value = pinfo.GetValue(Me,New Object() {Int32.MinValue})    ' I don't kNow how old i am '

编辑2:感谢@Rup现在我知道GetIndexParameters是缺失的部分.因此,以下应适用于任何类型的参数.

Dim pinfo As Reflection.PropertyInfo = Me.GetType.GetProperty("Foo")
Dim parameters() As Reflection.ParameterInfo = pinfo.GetIndexParameters()
Dim params(parameters.Length - 1) As Object
For i As Int32 = 0 To parameters.Length - 1
    Dim paramInfo As Reflection.ParameterInfo = parameters(i)
    If paramInfo.IsOptional Then
        params(i) = paramInfo.DefaultValue
    Else
        If paramInfo.ParameterType.IsValueType Then
            params(i) = Activator.CreateInstance(paramInfo.ParameterType)
        Else
            params(i) = nothing
        End If
    End If
Next
Dim value As Object = pinfo.GetValue(Me,params)

c# – 如何通过反射获取类及其父类的私有字段?

c# – 如何通过反射获取类及其父类的私有字段?

我有B类及其父类A,都在命名空间Domain中.

A类,有私人领域a;
B类,有私人字段b;

然后我在命名空间反射中有一个反射Util.
如果我使用这一行

instanceOfB.GetType().GetFields(BindingFlags.NonPublic 
         | BindingFlags.Public | BindingFlags.Instance );

找到所有字段(a& b),我只得到b.但是当我做一个受保护或公开的时候,我也找到了.

我还需要做什么来找到基类的私有领域?

解决方法

这是 documented behaviour:

Specify BindingFlags.NonPublic to include non-public fields (that is,private,internal,and protected fields) in the search. Only protected and internal fields on base classes are returned; private fields on base classes are not returned.

如果您需要获取私人领域,您需要询问基本类型. (使用Type.BaseType查找基本类型,并调用GetFields.)

c# – 识别MethodInfo实例是否是属性访问器

c# – 识别MethodInfo实例是否是属性访问器

我正在使用 Castle DynamicProxy编写一个装饰代理.我需要代理拦截器拦截属性写(而不是读),所以我正在检查方法的名称:
public void Intercept(IInvocation invocation)
{
    if (invocation.Method.Name.StartsWith("set_")
    {
        // ...
    }

    invocation.Proceed();
}

现在这样做不错,但是我不喜欢我的代理对于实现属性的深入了解:我想用类似于以下的东西替换方法名称检查:

if (invocation.Method.IsPropertySetAccessor)

不幸的是,我的Google-fu已经失败了我.有任何想法吗?

解决方法

您可以检查是否存在此方法是setter(未测试)的属性:
bool isSetAccessor = invocation.Method.DeclaringType.GetProperties() 
        .Any(prop => prop.GetSetMethod() == invocation.Method)

(灵感取自Marc’s answer to a related question.)

C# 通过反射获取方法/类上的自定义特性

C# 通过反射获取方法/类上的自定义特性

  1.所有自定义属性都必须继承System.Attribute 

   2.自定义属性的类名称必须为 XXXXAttribute 即是已Attribute结尾

 

自定义属性QuickWebApi

[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
    public class QuickWebApiAttribute: Attribute
    {
        public QuickWebApiAttribute(string _serviceCode,string _controllerName,string _actionName)
        {
            ServicesCode = _serviceCode;
            ControllerName = _controllerName;
            ActionName = _actionName;
        }

        public string ServicesCode{ get; set; }
        public string ControllerName { get; set; }
        public string ActionName { get; set; }

        
    }

接口类

public interface ISchool
    {
        [QuickWebApi("SchoolServices", "School", "GetSchoolAll")]
        List<School> GetSchoolAll();
        [QuickWebApi("SchoolServices", "School", "GetSchoolListById")]
        List<School> GetSchoolListById(string schoolId);
    }

具体实现

static void Main(string[] args)
        {
      

            Type t = typeof(ISchool);
            //获取方法特性中ActionName为GetSchoolAll的特性
            var b = t.GetMethods().Single(p => CustomAttributeExtensions.GetCustomAttribute<QuickWebApiAttribute>(p).ActionName == "GetSchoolAll");
            QuickWebApiAttribute  qu= CustomAttributeExtensions.GetCustomAttribute<QuickWebApiAttribute>(b);
            //循环遍历
            foreach (MemberInfo p in t.GetMethods())
            {
                object[] Attribute1 = p.GetCustomAttributes(true);
                object[] Attribute2 = p.GetCustomAttributes(typeof(QuickWebApiAttribute), false);
                //获取遍历结果
                //QuickWebApiAttribute att = CustomAttributeExtensions.GetCustomAttribute<QuickWebApiAttribute>(p);
                string a = "";
            }


            Console.ReadKey();
        }

知识扩展

 1 public enum AttributeTargets  
 2    {  
 3        // 摘要:  
 4        //     可以对程序集应用特性。  
 5        Assembly = 1,  
 6        //  
 7        // 摘要:  
 8        //     可以对模块应用特性。  
 9        Module = 2,  
10        //  
11        // 摘要:  
12        //     可以对类应用特性。  
13        Class = 4,  
14        //  
15        // 摘要:  
16        //     可以对结构应用特性,即值类型。  
17        Struct = 8,  
18        //  
19        // 摘要:  
20        //     可以对枚举应用特性。  
21        Enum = 16,  
22        //  
23        // 摘要:  
24        //     可以对构造函数应用特性。  
25        Constructor = 32,  
26        //  
27        // 摘要:  
28        //     可以对方法应用特性。  
29        Method = 64,  
30        //  
31        // 摘要:  
32        //     可以对属性应用特性。  
33        Property = 128,  
34        //  
35        // 摘要:  
36        //     可以对字段应用特性。  
37        Field = 256,  
38        //  
39        // 摘要:  
40        //     可以对事件应用特性。  
41        Event = 512,  
42        //  
43        // 摘要:  
44        //     可以对接口应用特性。  
45        Interface = 1024,  
46        //  
47        // 摘要:  
48        //     可以对参数应用特性。  
49        Parameter = 2048,  
50        //  
51        // 摘要:  
52        //     可以对委托应用特性。  
53        Delegate = 4096,  
54        //  
55        // 摘要:  
56        //     可以对返回值应用特性。  
57        ReturnValue = 8192,  
58        //  
59        // 摘要:  
60        //     可以对泛型参数应用特性。  
61        GenericParameter = 16384,  
62        //  
63        // 摘要:  
64        //     可以对任何应用程序元素应用特性。  
65        All = 32767,  
66    }

 

今天关于c# – 如何通过反射获取基本方法的MethodInfo,而不是属性和事件?c#通过反射获取属性的值的讲解已经结束,谢谢您的阅读,如果想了解更多关于asp.net – 通过反射获取其getter具有可选值的属性的值、c# – 如何通过反射获取类及其父类的私有字段?、c# – 识别MethodInfo实例是否是属性访问器、C# 通过反射获取方法/类上的自定义特性的相关知识,请在本站搜索。

本文标签: