【发布时间】:2012-11-30 04:47:18
【问题描述】:
来自 Java 世界,使用泛型和 C# 进行编程常常令人头疼。喜欢这个:
interface ISomeObject { }
class SomeObjectA : ISomeObject { }
class SomeObjectB : ISomeObject { }
interface ISomething<T> where T : ISomeObject
{
T GetObject();
}
class SomethingA : ISomething<SomeObjectA>
{
public SomeObjectA GetObject() { return new SomeObjectA(); }
}
class SomethingB : ISomething<SomeObjectB>
{
public SomeObjectB GetObject() { return new SomeObjectB(); }
}
class SomeContainer
{
private ISomething<ISomeObject> Something;
public void SetSomething<T>(ISomething<T> s) where T : ISomeObject
{
Something = (ISomething<ISomeObject>)s;
}
}
class TestContainerSomething
{
static public void Test()
{
SomeContainer Container = new SomeContainer();
Container.SetSomething<SomeObjectA>(new SomethingA());
}
}
这会导致InvalidCastExceptionSomething = (ISomething<ISomeObject>)s;。在 Java 中,这会起作用,我什至可以使用(如果一切都失败了)泛型通配符 <?>。这在 C# 中是不可能的。
虽然这只是我用来解释问题的一个示例,但如何消除此异常?唯一的主要限制是 SomeContainer 不能是泛型类
** 注意 **:关于这个有很多问题,但没有一个(我能找到)解决非泛型类中的泛型类成员。
** 更新 **
在 SetSomething 方法中,我添加了以下几行:
Console.WriteLine(s.GetType().IsSubclassOf(typeof(ISomething<SomeObjectA>)));
Console.WriteLine(s.GetType().ToString() + " : " + s.GetType().BaseType.ToString());
foreach (var i in s.GetType().GetInterfaces())
{
Console.WriteLine(i.ToString());
}
令我惊讶的输出
False
SomeThingA : System.Object
ISomething`1[SomeObjectA]
这就是我得到这个异常的原因吗?
【问题讨论】: