【问题标题】:How to get the method GetCustomAttribute from MemberInfo?如何从 MemberInfo 中获取 GetCustomAttribute 方法?
【发布时间】:2021-12-24 07:41:20
【问题描述】:

我尝试对某些类型进行一些反思。

所以我有这个

 public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        [MethodForRun(RunCount = 3)]
        public void Print()
        {
            Console.WriteLine($"{FirstName} {LastName}");
        }


        [MethodForRun(RunCount =2)]
        public void SayHello()
        {
            Console.WriteLine($"Hello THere {FirstName}");
        }

        static void AttributeTest(Type type)
        {
            var allMethods = type.GetMethods();
            var methodWithAttributes = allMethods.Where(x => x.GetCustomAttribute(typeof(MethodForRunAttribute)) != null);
        }
    }

    public class MethodForRunAttribute:Attribute
    {
        public int RunCount { get; set; }
    }

它是关于方法 AttributeTest。

我做不到

x.GetCustomAttribute

我只能做 GetCustomAttributes - 所以复数。但不仅仅是 GetCustomAttribute。

rror    CS1061  'MethodInfo' does not contain a definition for 'GetCustomAttribute' and no accessible extension method 'GetCustomAttribute' accepting a first argument of type 'MethodInfo' could be found

我必须改变什么?

谢谢

还有图书馆

【问题讨论】:

  • 你想这样使用它:Where( e => Attribute.GetCustomAttribute(e, typeof(MethodForRunAttribute)))link
  • 是的,但我不能;x.GetCustomAttribute。我正在使用 .NET 5.0

标签: c# reflection


【解决方案1】:

??

using System.Reflection;

我有这个命名空间。但它没有使用它。于是我又加了。现在它可以工作了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多