ale*_*lex 4 .net c# windows generics casting
我有一个object[]
containig一些值。我想从中提取信息,但是我无法将数组(a WeakReference
)中的第二个对象强制转换为IList,其中T为数组中的第三个值。
看一下我的代码:
object[] vals = GetValues(); //vals[2] = WeakReference, vals[3] = Type of T, vals[4] = index in the list
IList<((Type)vals[3])> list = (IList<((Type)vals[3])>)(((WeakReference)vals[2]).Target); //This line does not even compile, seems like I'm doing something wrong..
object oo = list.ElementAt((int)vals[4]);
//Do something with oo...
Run Code Online (Sandbox Code Playgroud)
有什么建议可以将WeakReference的目标转换为T = vals [3]的IList接口吗?
您将如此多的异构信息打包到一个数组中,真是很奇怪。数组通常用于存储相同类型的元素。为什么不将数据封装为适当的类型?
但是要回答所提出的问题-在C#4中,您可以使用dynamic
:
var target = ((dynamic)vals[2]).Target;
if(target != null)
{
object oo = Enumerable.ElementAt(target, vals[4]);
//Do something with oo...
}
Run Code Online (Sandbox Code Playgroud)
(编辑:如果要最大程度地减少dynamic
此处的使用,WeakReference
请将其强制转换为a,然后将动态调用保留到最后。这样,类型安全性将被“最大化”。)
否则,您可以使用反射:
object target = ((WeakReference)vals[2]).Target;
if (target != null)
{
object oo = target.GetType()
.GetProperty("Item")
.GetValue(target, new[] { vals[4] });
//Do something with oo...
}
Run Code Online (Sandbox Code Playgroud)
(编辑:如果可以显式实现索引器,则可能需要使用接口映射。)