我需要使用要使用的函数来装饰大量枚举,如果它是这个枚举。我目前有这个:
public enum AnimalType
{
[CustomSet(Helpers.ToUpper)]
Dog,
Snake,
Bird
}
public class CustomSet : Attribute
{
public Func<string, string> Function { get; set; }
public CustomSet(Func<string, string> function)
{
Function = function;
}
public string GetFix (string value)
{
return Function(value);
}
}
public static class Helpers
{
public static string ToUpper(string value)
{
return value.ToUpper();
}
}
但是,enum上的属性给出了错误
Error CS0181 Attribute constructor parameter 'function' has type 'Func<string, string>', which is not a valid attribute parameter type
我认为这是因为该方法不是本机类型。任何人都可以推荐更好的方法吗?
提前致谢
答案 0 :(得分:3)
没有 clean 方式来表达属性中的方法/委托。一种懒惰的方法可能是:
[CustomSet(typeof(Helpers), nameof(Helpers.ToUpper))]
即。您之后用于通过反射解析实际方法的Type
/ string
对。但是,我想知道更好的方法是否可以使属性本身成为&#34; doer of things&#34;,即
abstract class FormatAttribute : Attribute {
public abstract string Format(string value);
}
class UpperCaseAttribute : FormatAttribute {
public override string Format(string value) => value.ToUpper();
}
使用:
[UpperCase]
Dog,
现在,当您通过GetCustomAttribute
使用反射寻找抽象FormatAttribute
时,您将获得具体的实例(在这种情况下:UpperCaseAttribute
,尽管你不会知道的。)只需在您获得的属性上调用.Format(...)
方法。
答案 1 :(得分:2)
您可以创建Dictionary<AnimalType, Func<string, string>>
:
public static readonly Dictionary<AnimalType, Func<string, string>> AnimeTypeMappers =
new Dictionary<AnimalType, Func<string, string>>() {
{AnimalType.Dog, Helpers.ToUpper}
};
现在你可以像这样得到Func
:
AnimalTypeMappers[AnimalType.Dog]