【问题标题】:Call method with custom attribute [duplicate]具有自定义属性的调用方法[重复]
【发布时间】:2022-01-18 10:04:49
【问题描述】:

我正在尝试创建一个通用方法,并且我想在调用它时传递一个属性。是可能的还是只有在声明时才有可能?

代码:

public Window()
{
   //Is it possible do this?:
   [CustomAttribute(typeof(Something))]
   MyGenericMethod();
}

private void MyGenericMethod()
{
   //do stuff...
   //retrieve type from CustomAttribute
}

public class CustomAttribute : Attribute
{
   public CustomAttribute(Type type)
   {
   }
}

【问题讨论】:

  • 属性是一种将元数据与代码相关联的方法。如果您想在运行时将任何内容传递给您的方法,您应该查看参数而不是属性。你想达到什么目的?
  • 我想调用另一个类中的 MyGenericMethod 并传递一个类型但不通过方法参数
  • 但是为什么?最终目标是什么?为什么不能使用参数?见X/Y problem

标签: c# attributes custom-attributes


【解决方案1】:

简短的回答是否定的。属性用于关联元数据,或添加声明性信息。因此,在调用方法时不能调用属性。你可以在这里阅读更多关于它们的信息:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/

我认为您将不得不针对您的问题审查您的解决方案并找到不同的方法。

【讨论】:

    【解决方案2】:

    我不认为这是可能的,但你可以使用泛型方法。

    https://docs.microsoft.com/it-it/dotnet/csharp/programming-guide/generics/generic-methods

    【讨论】:

      猜你喜欢
      • 2013-04-10
      • 2018-07-30
      • 2018-07-28
      • 2011-03-28
      • 1970-01-01
      • 2021-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多