【问题标题】:Why does this code not compile, although interfaces are reference types?尽管接口是引用类型,但为什么这段代码无法编译?
【发布时间】:2013-07-13 01:05:21
【问题描述】:

我很困惑。在Why are interfaces in .Net reference types? 中,据说.Net 中的接口是引用类型。 第一个代码 sn -p 无法编译。它说类似“T 必须是引用类型...”

    public ISomeInterface DoMagic<T>(Expression<Func<object>> action, Tuple<string, DateTime, decimal> tuple) 
    where T : ISomeInterface 
    {
      Magician m = new Magician();
      return m.Magic<T>(()=> action, tuple.Item3);
    }

第二个编译。

    public ISomeInterface DoMagic<T>(Expression<Func<object>> action, Tuple<string, DateTime, decimal> tuple) 
    where T : class, ISomeInterface 
    {
      Magician m = new Magician();
      return m.Magic<T>(()=> action, tuple.Item3);
    }

如果接口是引用类型,为什么第一个代码 sn-p 无法编译?

【问题讨论】:

  • 值类型也可以实现接口。

标签: c# .net


【解决方案1】:

因为它是关于封装在接口内部的对象的 real 类型。 通过仅声明 ISomeInterface ,您没有定义 must 条件:T 必须是引用类型。

因为我可以拥有:

public interface IStructInterface {
}
public struct A : IStructInterface {
}

这是一个类型。

通过定义额外的约束class,你声明这个引用类型。

【讨论】:

    【解决方案2】:

    这是您在Magic 具有class 约束时收到的错误消息:

    public ISomeInterface Magic<T>(Func<object> a, decimal d) where T:class
    

    它的措辞可以更好,但是当它说“T 必须是一个引用类型......”时,它的实际意思是“T 被限制为一个类”。此代码生成与 OP 相同的错误:

     class ABC {  
        public ISomeInterface DoMagic<T>(Expression<Func<object>> action, Tuple<string, DateTime, decimal> tuple)
        where T : ISomeInterface
        {
            Magician m = new Magician();
            return m.Magic<T>(() => action, tuple.Item3);
        }
    }
    
    interface ISomeInterface { }
    
    class Magician
    {
        public ISomeInterface Magic<T>(Func<object> a, decimal d) where T:class
        {
            throw new NotImplementedException();
        }
    }
    

    类型“T”必须是引用类型才能在泛型类型或方法“ConsoleApplication4.Magician.Magic&lt;T&gt;(System.Func&lt;object&gt;, decimal)”中用作参数“T

    【讨论】:

      猜你喜欢
      • 2021-09-26
      • 1970-01-01
      • 2019-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-06
      • 2013-08-08
      相关资源
      最近更新 更多