【发布时间】:2016-09-21 14:03:19
【问题描述】:
我基本上有以下课程(示例见C# creating an implicit conversion for generic class?)。
class MyClass<T>
{
public MyClass(T val)
{
Value = val;
}
public T Value { get; set; }
public static implicit operator MyClass<T>(T someValue)
{
return new MyClass<T>(someValue);
}
public static implicit operator T(MyClass<T> myClassInstance)
{
return myClassInstance.Value;
}
}
可以做到
MyClass<IFoo> foo1 = new Foo();
MyClass<Foo> foo2 = new Foo();
//But not
MyClass<IFoo> foo3 = (IFoo)new Foo();
真正的问题发生在尝试做类似的事情时
void Bar(IFoo foo)
{
Bar2(foo);
//What should be the same as
Bar2<IFoo>(new MyClass<IFoo>(foo));
}
void Bar2<T>(MyClass<T> myClass)
{
//Do stuff
}
我如何重构 MyClass 以便在只知道接口的情况下使用对象?
【问题讨论】:
-
我不明白你真正想用这个实现什么。 MyClass 总是使用 IFoo 对象(接口和实现)还是可以使用其他任何东西?无论如何,如果你试图隐式转换接口,在 C# 中是不可能的(正如@EricLippert 已经说过的)
-
会有多个 IFoo 实现(Foo1、Foo2、.. FooN)。可能还有其他接口 Bar(OtherInterface other) { Bar2
(other); } 当然,这个问题是实际问题的精简版。
标签: c# generics implicit-conversion