我想用反射來恢復類型信息。我有給定一個集合對象,想分配給一個特定類型的局部變量
public Foo(object coll, string tValue)
{
var x = col1 as IList;
if (x != null)
x.Action();
var y = col1 as IDictionary;
if (y != null)
y.Action();
}
但是想有
public Foo(object coll, string tValue)
{
var x = col1 as IList<TValue>;
if (x != null)
x.Action();
var y = col1 as IDictionary<int, TValue>;
if (y != null)
y.Action();
}
是否有可能在到達和使用通用接口,而不是老派非泛型集合接口,只給出所包含的類名?
一旦建立了局部變量類型,我想避免在循環集合時支付反射和動態調用懲罰。
另一個例子,也許更加清晰:
var list = new Dictionary<int, MyObject>();
list.Add(100, new MyObject());
object listObject = list;
var x = listObject as IDictionary<int, dynamic>;
if (x != null)
{
foreach (var entry in x)
{
Console.WriteLine(entry.Key);
Console.WriteLine(entry.Value);
}
}
x是空...
快速評論,您可以使用「is」關鍵字而不是Blah!= null。 – Bashwork
我認爲Bashwork的觀點是你可以做'if(col1是IList)((IList)col1).Action();' –
在你調用這個函數的地方已知類型嗎?是否可以使用泛型(即,使Foo函數通用)。 – wllmsaccnt