2009-01-15 31 views

回答

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...   
} 
+0

不,它不會。 – Micah 2009-01-15 15:13:33

1

我完全不明白爲什麼你要對類屬性。那豈不是更加明顯,將其添加到屬性,像這樣:

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

你可以訪問使用這東西像值

var identity = objectThatHasAnIdentity.GetId(); 

GetId現在可能是一個擴展方法上object實現類似於Marc上面貼出的代碼

相關問題