我有一個接口:轉換一個對象到一個泛型類不知道類型
public interface IEntityWithTypedId<T>{
T Id { get; }
}
而且有兩類:
public abstract class EntityWithTypedId<TId> : IEntityWithTypedId<TId>{...}
public abstract class Entity : EntityWithTypedId<int>{...}
所以,我有實體這樣的:
public class TestA : Entity
public class TestB : EntityWithTypedId<string>
public class TestC : EntityWithTypedId<byte>
現在我有一個對象並需要將它投射到IEntityWithTypedId<T>
我可以這樣做嵌套ifs,檢查對象類型。但我正在尋找一個通用的解決方案。
我需要得到標識值(字符串,所以我不關心什麼是T)
例子:
var idString = ((IEntityWithTypedId<long>)object).Id.ToString();
這可能嗎?
如果你不知道'T'甚至作爲一個泛型類型參數,你會怎麼想到用它?也許你應該有一個非泛型的接口,你可以將其轉換爲(或者也可以)... – 2014-10-16 17:44:03
我的IEntityWithTypedId有一個屬性Id,我需要將該值作爲一個字符串(所以我不在乎T)。這樣的事情︰var id =((IEntityWithTypedId)object).Id.ToString() –
Paul
2014-10-16 17:51:13
對,所以你應該有一個非通用的接口,因爲我建議... – 2014-10-16 18:04:54