C# 使用泛型检索属性
给定我的项目中的重复代码,格式为:C# 使用泛型检索属性,c#,generics,attributes,C#,Generics,Attributes,给定我的项目中的重复代码,格式为: public static ReasonAttributes GetAttributes(this Reason value) { var type = value.GetType(); var name = Enum.GetName(type, value); if (name == null) return null; var field = type.GetField(name); if (field == nul
public static ReasonAttributes GetAttributes(this Reason value)
{
var type = value.GetType();
var name = Enum.GetName(type, value);
if (name == null) return null;
var field = type.GetField(name);
if (field == null) return null;
return Attribute.GetCustomAttribute(field, typeof(ReasonAttributes)) as ReasonAttributes;
}
是否可以创建泛型以避免重复代码?大致如下:
public static T GetAttribute<T, T1>(T1 value)
{
var type = value.GetType();
var name = Enum.GetName(type, value);
if (name == null) return default(T);
var field = type.GetField(name);
if (field == null) return default(T);
return Attribute.GetCustomAttribute(field, typeof(T)) as T;
}
publicstaticgetattribute(T1值)
{
var type=value.GetType();
var name=Enum.GetName(类型、值);
if(name==null)返回默认值(T);
var field=type.GetField(名称);
if(field==null)返回默认值(T);
返回Attribute.GetCustomAttribute(field,typeof(T))作为T;
}
我在返回行中得到错误:
The type parameter <T> cannot be used with the `as` operator because it does not have a class type constraint nor a `class` constraint.
类型参数不能与`as`运算符一起使用,因为它既没有类类型约束,也没有`class`约束。
很简单,只需添加一个类型约束,即T
必须从属性继承
public static T GetAttribute<T>(object value)
where T : Attribute
{
var type = value.GetType();
var name = Enum.GetName(type, value);
if (name == null) return default(T);
var field = type.GetField(name);
if (field == null) return default(T);
return Attribute.GetCustomAttribute(field, typeof(T)) as T;
}
publicstaticgetattribute(对象值)
其中T:Attribute
{
var type=value.GetType();
var name=Enum.GetName(类型、值);
if(name==null)返回默认值(T);
var field=type.GetField(名称);
if(field==null)返回默认值(T);
返回Attribute.GetCustomAttribute(field,typeof(T))作为T;
}
你根本不需要T1
;您可以对任何内容调用GetType()
(当然null
除外)。您甚至从未在方法体中使用过T1
,因此很明显,参数的类型无关紧要
其中T:class
也可以工作,但您也可以让编译器阻止有人不经意地调用GetAttribute()
您是否应该在方法定义中添加where t:class
,以便您的代码知道t can是一个类并且可以实例化
public static T GetAttribute<T, T1>(T1 value) where T : class
{
var type = value.GetType();
var name = Enum.GetName(type, value);
if (name == null) return default(T);
var field = type.GetField(name);
if (field == null) return default(T);
return Attribute.GetCustomAttribute(field, typeof(T)) as T;
}
publicstatict GetAttribute(T1值),其中T:class
{
var type=value.GetType();
var name=Enum.GetName(类型、值);
if(name==null)返回默认值(T);
var field=type.GetField(名称);
if(field==null)返回默认值(T);
返回Attribute.GetCustomAttribute(field,typeof(T))作为T;
}
比我的答案好得多。干得好,先生:-)