2017-04-25 138 views
-1

我有这种类型的变量:方法,返回匿名类型C#

enter image description here

我应该写我的方法是什么样的回报类型的?我写了object但它没有解决。谢谢。

编辑:

我做了这样的类:

public class IlIlceTarife 
{ 
    public string Il { get; set; } 
    public string Ilce { get; set; } 
    public string Tarife { get; set; } 
} 

public class a 
{ 
    public IlIlceTarife Name { get; set; } 
    public int Sayi { get; set; } 
} 

而且我做的返回类型为这样:

public List<IEnumerable<a>> TarifeGiver1(string il, string ilce) 

而且VS给了这个错误:

> Cannot implicitly convert type 
> 'System.Collections.Generic.List<System.Collections.Generic.IEnumerable<<anonymous 
> type: <anonymous type: string Il, string Ilce, string Tarife> Name, 
> int Sayi>>>' to 
> 'System.Collections.Generic.List<System.Collections.Generic.IEnumerable<WebApplication2.Controllers.a>>' 
+0

编写类来代替。 –

+1

为什么你给一个班级一个名字'a'?这是我可以想象得出的最无名的名字 –

+0

@TimSchmelter我以后会改变它。只是写了很快。 – jason

回答

0

你不应该返回一个一致的类型。相反,您应该创建一个常规命名类并将其用作返回类型。

匿名类型都不错时,他们的范围仅仅是方法本身里面。在方法之外他们没有用处。例如,如果他们的定义不公开?唯一的解决方案是创建一个类。

如果你仍然想要返回一个匿名类型,你应该返回objectdynamic,我对使用它作为返回类型并不满意。


关于你的更新:你必须在初始化实例的代码中使用命名类型(可能是LINQ)。 C#不会自动将匿名类型转换为命名类型。

+0

请参阅我的编辑。我已经完成了你所说的,但它给了错误。 – jason

+0

查看我的更新... –

+0

正如蒂姆所说:给班级一个真实的名字。 –