この定義を考えると:
[UniqueId("Ident")]
public class MyClass : MyBase
{
public int Ident{ get; }
}
「MyBase」クラスから「UniqueId」属性を取得し、一致するプロパティ名を見つけて、基になる値を取得するための最良の方法は何ですか?
この定義を考えると:
[UniqueId("Ident")]
public class MyClass : MyBase
{
public int Ident{ get; }
}
「MyBase」クラスから「UniqueId」属性を取得し、一致するプロパティ名を見つけて、基になる値を取得するための最良の方法は何ですか?
基本クラスの抽象メソッド/プロパティの方が適切ではないでしょうか?
public abstract int UniqueId {get;}
次のように、属性を介して:
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...
}
クラスでその属性が必要な理由が正確にはわかりません。次のように、プロパティに追加する方が明白ではないでしょうか。
public class MyClass
{
[UniqueId]
public int Ident{ get; }
}
次のようなものを使用してこの値にアクセスできます
var identity = objectThatHasAnIdentity.GetId();
GetId
object
マークが上に投稿したものと同様のコードを実装する拡張メソッドになる可能性があります