Ale*_*lex 29 .net c# custom-attributes
我有以下自定义属性,可以应用于属性:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class IdentifierAttribute : Attribute
{
}
Run Code Online (Sandbox Code Playgroud)
例如:
public class MyClass
{
[Identifier()]
public string Name { get; set; }
public int SomeNumber { get; set; }
public string SomeOtherProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
还有其他类,Identifier属性可以添加到不同类型的属性中:
public class MyOtherClass
{
public string Name { get; set; }
[Identifier()]
public int SomeNumber { get; set; }
public string SomeOtherProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后,我需要能够在我的消费类中获取此信息.例如:
public class TestClass<T>
{
public void GetIDForPassedInObject(T obj)
{
var type = obj.GetType();
//type.GetCustomAttributes(true)???
}
}
Run Code Online (Sandbox Code Playgroud)
解决这个问题的最佳方法是什么?我需要得到[标识符()]字段(整型,字符串等)和实际值,显然基于该类型的类型.
Ric*_*end 39
像下面的东西来说,这将只使用它涉及防空火炮具有属性的第一属性,当然你可以把它放在一个以上..
public object GetIDForPassedInObject(T obj)
{
var prop = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)
.FirstOrDefault(p => p.GetCustomAttributes(typeof(IdentifierAttribute), false).Count() ==1);
object ret = prop !=null ? prop.GetValue(obj, null) : null;
return ret;
}
Run Code Online (Sandbox Code Playgroud)