gpt4 book ai didi

c# - 实现接口(interface)的数组的隐式类型化

转载 作者:太空狗 更新时间:2023-10-29 17:38:37 25 4
gpt4 key购买 nike

我的印象是,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# 编译器考虑所有指定元素的类型集。它考虑公共(public)基类型等。

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

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

...但我个人只使用显式形式:

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

或者,如果您将 obj1obj2obj3 中的任何一个或全部显式声明为 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

Tr M<X>(X x1 … X xm)

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.

关于c# - 实现接口(interface)的数组的隐式类型化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2799902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com