C# 将泛型实例强制转换为非泛型实例
我有一个定义如下的类:C# 将泛型实例强制转换为非泛型实例,c#,generics,types,C#,Generics,Types,我有一个定义如下的类: class ProxyWithSetter<T> : ProxyValue where T : Value 强制转换返回null,因为p不是类型proxyWithTester,但无法知道它的确切类型。我也不知道val的确切类型。只要知道它确实是一个值 我能理解为什么它不起作用。我只是在寻找一个可行的解决办法 您可以使用 p.GetType() 使用它,您将得到一个类型对象,其字符串表示形式类似于 ProxyWithSetter[Value] 您可以使用访
class ProxyWithSetter<T> : ProxyValue where T : Value
强制转换返回null,因为p
不是类型proxyWithTester
,但无法知道它的确切类型。我也不知道val
的确切类型。只要知道它确实是一个值
我能理解为什么它不起作用。我只是在寻找一个可行的解决办法 您可以使用
p.GetType()
使用它,您将得到一个类型对象,其字符串表示形式类似于
ProxyWithSetter[Value]
您可以使用访问泛型类型
p.GetType().GenericTypeArguments
由所有类型对象组成的数组,这些对象是类的泛型参数。
那就检查一下
p.getType().GenericTypeArguments == typeof(Value)
你不能按你的要求去做。即使您创建了一个包含
Setter
(必须是属性,而不是字段)的逆变接口,它也只能获取T
或更多派生类型的项
例如,如果您有一个子类Value
的类SuperValue
,然后您有一个ProxyWithSetter
的实例,则无法将Value
的实例传递给它。它必须是SuperValue
或子类化的SuperValue
因此,问题在于并非每个
ProxyWithSetter
都能接受值类型的输入,输入到它的设置器中
您可以创建以下界面:
interface IProxyWithSetter
{
Action<Value> Setter { get; }
}
接口IProxyWithSetter
{
动作设置程序{get;}
}
并实施类似于:
class ProxyWithSetter<T> : ProxyValue, IProxyWithSetter where T : Value
{
Action<Value> IProxyWithSetter.Setter { get { return x => this.Setter((T)x); } }
//other things
}
class-ProxyWithSetter:ProxyValue,IProxyWithSetter,其中T:Value
{
操作IProxyWithSetter.Setter{get{return x=>this.Setter((T)x);}
//其他事情
}
这样,在静态已知类型的上下文中,您的Setter
将采用T
,但在您所说的方法中,您可以像IProxyWithSetter
那样执行,然后调用Setter(val)
最初是什么类型的p?(我不明白行动的意义何在)行动是一个领域。当创建实例时,它被设置为某个具体类型,但随后所有这些实例都被推到一个列表中,该具体类型将丢失。但实际检查哪个ProxyValue是ProxyWithBetter并不是问题所在。在我的解决方案中,我以不同的方式解决了这个问题。问题是,我需要将它转换为“true”类型,以便可以调用它作为字段的泛型函数。此外,我需要向该函数传递一个值,因此即使我成功地将其强制转换,我仍然需要将该值强制转换为适当的类型…我已经尝试过了。当类型(包括泛型参数)正确时,一切正常。你能提供崩溃代码吗?这与我的最终解决方案非常接近(也许更优雅)。我将把它标为可接受的答案。
interface IProxyWithSetter
{
Action<Value> Setter { get; }
}
class ProxyWithSetter<T> : ProxyValue, IProxyWithSetter where T : Value
{
Action<Value> IProxyWithSetter.Setter { get { return x => this.Setter((T)x); } }
//other things
}