我現在做:鑄造泛型類型的非泛型方法
void Main()
{
var command1 = new PersistenceCommand(new MyIntBO());
var command2 = new PersistenceCommand(new MyGuidBO());
var command3 = new PersistenceCommand(new PersistentBO());
Console.WriteLine(command1.ToString());
Console.WriteLine(command2.ToString());
Console.WriteLine(command3.ToString());
}
public class PersistenceCommand
{
public PersistenceCommand(PersistentBO businessObject)
{
_businessObject = businessObject;
}
public override string ToString()
{
string result = _businessObject.GetType().Name;
var keyed = _businessObject as IPrimaryKeyed<int>;
if (keyed != null)
{
result += " " + keyed.Id.ToString();
}
return result;
}
private readonly PersistentBO _businessObject;
}
public interface IPrimaryKeyed<out TKey>
{
TKey Id { get; }
}
public class PersistentBO {}
public class MyIntBO : PersistentBO, IPrimaryKeyed<int>
{
public int Id { get { return 1008; } }
}
public class MyGuidBO : PersistentBO, IPrimaryKeyed<Guid>
{
public Guid Id
{
get
{
return new Guid("6135d49b-81bb-43d4-9b74-dd84c2d3cc29");
}
}
}
此打印:
MyIntBO 1008 MyGuidBO PersistentBO
我想它想打印:
MyIntBO 1008 MyGuidBO 6135d49b-81bb-43d4-9b74-dd84c2d3cc29 PersistentBO
什麼是最優雅的方式來做到這一點?
我想支持所有類型的鍵 - int
,long
,Guid
等 - 所以我寧願不做多個演員。請注意,並非每個業務對象都實現該接口(有些沒有單個主鍵)。
我意識到我可以使用反射並嘗試訪問Id
屬性。我想知道是否有更好的解決方案。
澄清:爲了解決@Acaz索薩和@Petar伊萬諾夫的答案,我們有幾十個散落在已經實現IPrimaryKeyed<T>
多個組件類。我不想通過擴展接口合約來打破所有這些問題。如果我從頭開始設計,他們的解決方案就可以工作。
+1 - 如果我走這條路線,可以節省一些時間。請注意'stuff'應該是'_businessObject'。我也可以緩存'GetType()'的結果。 – TrueWill
對錯字很好,固定 –
這就是我最終使用的。我爲CanRead添加了一個檢查,並且GetValue的結果不爲null。 – TrueWill