1

この定義を考えると:

[UniqueId("Ident")]
public class MyClass : MyBase
{
    public int Ident{ get; }
}

「MyBase」クラスから「UniqueId」属性を取得し、一致するプロパティ名を見つけて、基になる値を取得するための最良の方法は何ですか?

4

2 に答える 2

2

基本クラスの抽象メソッド/プロパティの方が適切ではないでしょうか?

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...         
}
于 2009-01-15T15:12:04.393 に答える
1

クラスでその属性が必要な理由が正確にはわかりません。次のように、プロパティに追加する方が明白ではないでしょうか。

public class MyClass
{
    [UniqueId]
    public int Ident{ get; }
}

次のようなものを使用してこの値にアクセスできます

var identity = objectThatHasAnIdentity.GetId();

GetIdobjectマークが上に投稿したものと同様のコードを実装する拡張メソッドになる可能性があります

于 2009-01-15T15:47:15.150 に答える