C# 是否可以在不传递约束类型的情况下检索约束类型的泛型参数?
我有以下函数用于检索枚举中给定类型属性的值:C# 是否可以在不传递约束类型的情况下检索约束类型的泛型参数?,c#,generics,C#,Generics,我有以下函数用于检索枚举中给定类型属性的值: public interface IAttribute<T> { T Value { get; } } public static class EnumExtensions { public static TAttributeValue GetAttribute<TAttribute, TAttributeValue>(this Enum enumValue) where TAttribute : IAttr
public interface IAttribute<T>
{
T Value { get; }
}
public static class EnumExtensions
{
public static TAttributeValue GetAttribute<TAttribute, TAttributeValue>(this Enum enumValue) where TAttribute : IAttribute<TAttributeValue>
{
var enumType = enumValue.GetType();
var field = enumType.GetField(enumValue.ToString());
var attributes = field.GetCustomAttributes(typeof(TAttribute), false);
return attributes.Length == 0
? default(TAttributeValue)
: ((TAttribute)attributes[0]).Value;
}
}
公共接口属性
{
T值{get;}
}
公共静态类枚举扩展
{
公共静态TAttributeValue GetAttribute(此枚举enumValue),其中TatAttribute:IAtAttribute
{
var enumType=enumValue.GetType();
var field=enumType.GetField(enumValue.ToString());
var attributes=field.GetCustomAttributes(typeof(tatAttribute),false);
返回属性。长度==0
?默认值(TAttributeValue)
:((TatAttribute)属性[0])。值;
}
}
这样使用:
public class GenericStringAttribute : Attribute, IAttribute<string>
{
private readonly string value;
public GenericStringAttribute(string value)
{
this.value = value;
}
public string Value
{
get { return this.value; }
}
}
public enum Thing
{
[GenericString("thing's value")]
Thing = 0,
}
public static class ThingExtensions
{
public static string GetGenericStringValue(this Thing enumThing)
{
return enumThing.GetAttribute<GenericStringAttribute, string>();
}
}
public类GenericStringAttribute:Attribute,IAttribute
{
私有只读字符串值;
公共GenericStringAttribute(字符串值)
{
这个值=值;
}
公共字符串值
{
获取{返回this.value;}
}
}
公共枚举事件
{
[GenericString(“事物的价值”)]
事物=0,
}
公共静态类ThingExtensions
{
公共静态字符串GetGenericStringValue(这个东西)
{
返回enumThing.GetAttribute();
}
}
但是我不禁想知道是否可以以某种方式删除
GetAttribute()
的第二个类型参数,因为该类型信息存储为第一个类型参数t(或第一个类型的父级)的泛型参数。我发现很难尝试,因为我显然需要两种类型定义,而且似乎无法约束到“继承自IAttribute
”的变量泛型类型,同时仍然掌握IAttribute的原始类型和泛型参数的类型。如果1.)编译的代码2.)您使用了比K
和t
更好的名称您的泛型类型参数。请记住,对于不同的泛型参数,一个类型可能会多次实现同一接口。。。如果不指明泛型参数(示例中的K),您如何知道您想要哪一个?很抱歉,它没有编译,是从我正在研究的东西中提取的,并且没有校对好。固定的@我想我从来没有想过。这是正确的。在这种结构中,我认为不可能多次实现这个接口,因为每个实现都会隐藏上一个,所以我没有想到。我想没有办法指定接口对其通用实现是互斥的,并相应地进行约束,是吗?@WesleyWigham肯定有。显式接口实现。我甚至不知道这是可能的。那太好了。