C# 在C中的方法上下文中无法识别列表实例#

C# 在C中的方法上下文中无法识别列表实例#,c#,list,compiler-errors,ienumerable,C#,List,Compiler Errors,Ienumerable,我试图理解为什么在这个上下文中,当我尝试使用“List”特定的方法“Add”时,编译器会抛出一个错误。错误解释指出这是由于字段定义造成的。(IEnumerable不包括“Add”方法)但是,我在内部上下文中更新了它。请给我一个合理的解释,我将不胜感激 注意:我知道这是因为IEnumerable是一个接口,我可以使用IList。然而,我不能理解的是,编译器应该在内部上下文中提取类型,但它不是 class Program { private static IEnumerable<str

我试图理解为什么在这个上下文中,当我尝试使用“List”特定的方法“Add”时,编译器会抛出一个错误。错误解释指出这是由于字段定义造成的。(IEnumerable不包括“Add”方法)但是,我在内部上下文中更新了它。请给我一个合理的解释,我将不胜感激

注意:我知道这是因为IEnumerable是一个接口,我可以使用IList。然而,我不能理解的是,编译器应该在内部上下文中提取类型,但它不是

class Program
{
    private static IEnumerable<string> exampleList;
    public static void Main()
    {
        exampleList = new List<string>();
        exampleList.Add("ex"); // ==> Compiler Error Here.
    }
}
类程序
{
私有静态IEnumerable示例列表;
公共静态void Main()
{
exampleList=新列表();
exampleList.Add(“ex”);//=>此处出现编译器错误。
}
}

按以下方式更改代码将解决问题

private static List<string> exampleList;

您的
示例列表
定义为
IEnumerable
,因此其编译时类型为
IEnumerable
。因此,当编译器编译代码时,它只能知道它是一个
IEnumerable

存在两个主要修复方法:

1) 将exampleList声明为IList

private static IList<string> exampleList;
私有静态IList示例列表;
2) 使用临时变量设置列表内容

public static void Main()
{
    var list = new List<string>();
    list.Add("ex");
    exampleList = list;
}
publicstaticvoidmain()
{
var list=新列表();
列表。添加(“ex”);
示例列表=列表;
}
<> >简单地解释编译器为什么只能知道它是iNeXBIT的,请考虑下面的代码:

IEnumerable<string> exampleList;

if (TodayIsAWednesday()) 
{
    exampleList = new List<string>();
}
else 
{
    exampleList = new string[0];
}

// How can the compiler know that exampleList is a List<string>? 
// It can't!
exampleList.Add("ex");
IEnumerable示例列表;
如果(今天是星期三())
{
exampleList=新列表();
}
其他的
{
exampleList=新字符串[0];
}
//编译器如何知道exampleList是一个列表?
//不可能!
示例列表。添加(“ex”);
正如您所看到的,“I”意味着它是一个接口。它可以接受所有类型的枚举,但没有Add的方法。
您可以看到:

错误消息是特定的,并解释了问题
IEnumerable
没有
Add
方法。您的意思是将
示例列表
声明为
列表
吗?这就是OOP中的封装。我不明白的是编译器为什么不在内部上下文中提取类型,但现在我意识到这是因为newing操作在运行时,所以编译器会抛出一个错误,谢谢。Upvoted,我只是想添加一个类似于后一个代码段的答案。谢谢,但我不明白的是,编译器应该在内部上下文中提取类型,但它不是。我已经用IList而不是IEnumerable解决了这个问题。@skynyrd简单地说:它不是这样工作的。如果变量是为特定类型定义的,则只能使用该特定类型的方法。
IEnumerable<string> exampleList;

if (TodayIsAWednesday()) 
{
    exampleList = new List<string>();
}
else 
{
    exampleList = new string[0];
}

// How can the compiler know that exampleList is a List<string>? 
// It can't!
exampleList.Add("ex");