如何将Func放入C#属性(注释)中? [英] How do you put a Func in a C# attribute (annotation)?
问题描述
我有一个C#注释:
[AttributeUsage(AttributeTargets.Method)]
public class OperationInfo : System.Attribute {
public enum VisibilityType {
GLOBAL,
LOCAL,
PRIVATE
}
public VisibilityType Visibility { get; set; }
public string Title { get; set; }
public Func<List<string>, List<string>> Func;
public OperationInfo(VisibilityType visibility, string title, Func<List<string>, List<string>> function) {
Visibility = visibility;
Title = title;
Func = function;
}
}
如您所见,有一个属性是Func,我想动态地调用它.基本上,我想解析所有具有此批注的方法,然后调用绑定到该批注的Func.
As you can see, there is a property which is a Func and I want to call it dynamically. Basically, I'd like to parse all the methods which have this annotation and then call the Func binded to the annotation.
我想这样使用它(这是echo函数的简单示例,它获取一个字符串并返回相同的字符串):
I'd like to use it like this (this is a simple example of an echo function, which gets a string and return the same string):
[OperationInfo(OperationInfo.VisibilityType.GLOBAL, "echo", IDoEcho)]
public static string DoEcho(string a)
{
return a;
}
[OperationInfo(OperationInfo.VisibilityType.PRIVATE, null, null)]
public static List<string> IDoEcho(List<string> param) {
return new List<string>() { DoEcho(param[0]) };
}
我的Annotation类没有任何错误,但是当涉及到重新生成整个解决方案时,每次我声明带有注释的方法时,都会出现一个错误,告诉我必须在注释中使用文字.
I've got no error in my Annotation class but when it comes to regenerate the entire solution, each time I declare a method with the annotation I've got an error which tells me that I must use literals in an annotation.
我知道有局限性,但是有什么办法可以避免这个问题?我知道我可以使用字符串代替Func,并动态查找名称与字符串相同的函数,但是我不想这样做.
I understand there is limitations, but is there any way I can avoid this problem? I know I can use a string instead of a Func, and look dynamically for the function whose name is the same as the string, but I would like not to do so.
感谢您的帮助:)
推荐答案
我认为这是不可能的,c#仅允许您仅使用具有常量值的属性.
I don't think it is possible, c# only allows you to use Attributes with constant values only.
执行此操作的一种方法是创建一个类而不是一个func,然后将该类的类型传递给属性. 然后,您需要使用反射实例化它并在其中执行一个方法.
One way of doing this would be to create a class instead of a func, and then you pass the type of that class into the attribute. You'd then need to instantiate it with reflection and execute a method in it.
所以一个例子是:
public interface IDoStuff
{
IList<string> Execute();
}
然后您的属性将采用类型而不是Func
then your attribute would take a type instead of a Func
public OperationInfo(VisibilityType v, string title, Type type)
{
///...
}
然后,您将创建一个实现您的接口的类,并将其传递给属性.尽管这意味着(至少在最初,并且不知道您的问题),但是每次您想要返回不同的结果时,您都需要创建一个新类.
you then would create a class that implements your interface and pass it into the attribute. Although this would mean that (at least initially, and without knowing your problem) you will need to create a new class every time you want to return different results.
这篇关于如何将Func放入C#属性(注释)中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!