【发布时间】: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