1
鑑於這樣的定義:什麼是使用特定屬性獲取財產和價值的最佳方式?
[UniqueId("Ident")]
public class MyClass : MyBase
{
public int Ident{ get; }
}
什麼是從「MyBase」類獲得「唯一ID」屬性,找到匹配的屬性名,並獲得潛在價值的最佳方式是什麼?
鑑於這樣的定義:什麼是使用特定屬性獲取財產和價值的最佳方式?
[UniqueId("Ident")]
public class MyClass : MyBase
{
public int Ident{ get; }
}
什麼是從「MyBase」類獲得「唯一ID」屬性,找到匹配的屬性名,並獲得潛在價值的最佳方式是什麼?
基類中的抽象方法/屬性不是更合適嗎?
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
實現類似於Marc上面貼出的代碼
不,它不會。 – Micah 2009-01-15 15:13:33