Given this definition:
[UniqueId("Ident")]
public class MyClass : MyBase
{
public int Ident{ get; }
}
What is the best way from the "MyBase" class to get the "UniqueId" attribute, find the matching property name and get the underlying value?
Given this definition:
[UniqueId("Ident")]
public class MyClass : MyBase
{
public int Ident{ get; }
}
What is the best way from the "MyBase" class to get the "UniqueId" attribute, find the matching property name and get the underlying value?
Wouldn't an abstract method / property in the base-class be more suitable?
public abstract int UniqueId {get;}
Via attributes, like so:
object GetUniqueId() // or int
{
Type type = GetType();
UniqueIdAttribute attrib = null;
foreach(UniqueIdAttribute tmp in
type.GetCustomAttributes(typeof(UniqueIdAttribute), true))
{
attrib = tmp;
break;
}
if (attrib == null) throw new InvalidOperationException();
return type.GetProperty(attrib.PropertyName).GetValue(this, null);
// perhaps cast here...
}
I don't exactly understand why you'd want that attribute on the class. Wouldn't it be more obvious to add it to the property, like this:
public class MyClass
{
[UniqueId]
public int Ident{ get; }
}
You could access this value using something like
var identity = objectThatHasAnIdentity.GetId();
GetId could now be an extension method on object that implements a code similar to what Marc posted above