相关疑难解决方法(0)

隐式运算符使用接口

我有一个泛型类,我正在尝试实现隐式类型转换.虽然它主要起作用,但它不适用于界面转换.经过进一步调查,我发现存在编译器错误:"来自接口的用户定义转换"适用.虽然我知道在某些情况下应该强制执行,但我正在尝试做的事情似乎是合法的案例.

这是一个例子:

public class Foo<T> where T : IBar
{
    private readonly T instance;

    public Foo(T instance)
    {
        this.instance = instance;
    }
    public T Instance
    {
        get { return instance; }
    }
    public static implicit operator Foo<T>(T instance)
    {
        return new Foo<T>(instance);
    }
}
Run Code Online (Sandbox Code Playgroud)

使用它的代码:

var concreteReferenceToBar = new ConcreteBar();
IBar intefaceReferenceToBar = concreteReferenceToBar;
Foo<ConcreteBar> concreteFooFromConcreteBar = concreteReferenceToBar;
Foo<IBar> fooFromConcreteBar = concreteReferenceToBar;
Foo<IBar> fooFromInterfaceBar = intefaceReferenceToBar; // doesn't work
Run Code Online (Sandbox Code Playgroud)

有没有人知道一个解决方法,或者任何人都能以令人满意的方式解释为什么我不能施展 interfaceReferenceToBar隐式地Foo<IBar>,因为在我的情况下它没有被转换,只包含在Foo中?

编辑: 看起来协方差可能提供救赎.我们希望C#4.0规范允许使用协方差隐式转换接口类型.

c# compiler-construction generics casting implicit-conversion

53
推荐指数
1
解决办法
2万
查看次数

具有泛型的隐式运算符不适用于接口

我基本上有以下类(在C#上创建的示例为泛型类创建隐式转换?).

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

一个人可以做到

MyClass<IFoo> foo1 = new Foo();
MyClass<Foo>  foo2 = new Foo();

//But not
MyClass<IFoo> foo3 = (IFoo)new Foo();
Run Code Online (Sandbox Code Playgroud)

当尝试做类似的事情时,会出现真正的问题

void Bar(IFoo foo)
{
    Bar2(foo);
    //What should be the same as
    Bar2<IFoo>(new MyClass<IFoo>(foo));
}

void Bar2<T>(MyClass<T> …
Run Code Online (Sandbox Code Playgroud)

c# generics implicit-conversion

6
推荐指数
1
解决办法
1391
查看次数