加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 实现接口的数组的隐式类型

发布时间:2020-12-15 03:44:44 所属栏目:百科 来源:网络整理
导读:我的印象是,C#编译器将隐式地键入一个类型,它们都可以隐式转换为一个数组. 编译器生成 没有找到隐式类型数组的最佳类型 public interface ISomething {}public interface ISomething2 {}public interface ISomething3 {}public class Foo : ISomething { }pu
我的印象是,C#编译器将隐式地键入一个类型,它们都可以隐式转换为一个数组.

编译器生成
没有找到隐式类型数组的最佳类型

public interface ISomething {}

public interface ISomething2 {}

public interface ISomething3 {}

public class Foo : ISomething { }
public class Bar : ISomething,ISomething2 { }
public class Car : ISomething,ISomething3 { }

void Main()
{
    var obj1 = new Foo();
    var obj2 = new Bar();
    var obj3 = new Car();

    var objects= new [] { obj1,obj2,obj3 };
}

我知道纠正这个的方法是声明类型如下:

new ISomething [] { obj1,...}

但是我在这里的封面类型帮助之下.

解决方法

C#编译器考虑所有指定元素的一组类型.它不考虑常见的基本类型等

您可以转换其中一个表达式:

var objects= new [] { obj1,(ISomething) obj3 };

…但是个人我只是使用明确的形式:

var objects= new ISomething[] { obj1,obj3 };

或者,如果您明确声明obj1,obj2和obj3作为ISomething类型的任何或全部,那么在不更改数组初始化表达式的情况下也可以正常工作.

从C#3规范,第7.5.10.4节:

An array creation expression of the
third form is referred to as an
implicitly typed array creation
expression
. It is similar to the
second form,except that the element
type of the array is not explicitly
given,but determined as the best
common type (§7.4.2.13) of the set of
expressions in the array initializer.

7.4.2.13节如下所示:

In some cases,a common type needs to
be inferred for a set of expressions.
In particular,the element types of
implicitly typed arrays and the return
types of anonymous functions with
block bodies are found in this way.
Intuitively,given a set of
expressions E1…Em this inference
should be equivalent to calling a
method

06002

with the Ei as arguments. More precisely,the inference starts out with an unfixed type variable X. Output type inferences are then made from each Ei with type X. Finally,X is fixed and the resulting type S is the resulting common type for the expressions.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读