我有一个静态类,其方法使用linq并返回一个对象。我的编译器不想编译它,因为他需要该对象的定义。您能告诉我定义对象的观点吗?
我正在寻找一个微小的解决方案,我不想为其创建额外的类(如果不需要的话)
public static object GetWaveAnimation()
{
return (from element in configurations.Elements("Animation")
where element.Attribute("NAME").Value == "Wave"
select new
{
time = element.Attribute("TIMING").Value,
enable = element.Attribute("ENABLED").Value
}).FirstOrDefault();
}
最佳答案
对于.net 3.5而言,这是最干净的解决方案。
public struct Wave{
public X time;
public Y enable;
}
public static Wave GetWaveAnimation()
{
try
{
return (from element in configurations.Elements("Animation")
where element.Attribute("NAME").Value == "Wave"
select new Wave
{
time = element.Attribute("TIMING").Value,
enable = element.Attribute("ENABLED").Value
}).FirstOrDefault();
}
catch { return null; }
}
对于.net 4.0,您可以使用dynamic关键字(但是,由于匿名类型是内部的,因此无法从程序集或朋友程序集外部调用此方法。)
public static dynamic GetWaveAnimation()
{
try
{
return (from element in configurations.Elements("Animation")
where element.Attribute("NAME").Value == "Wave"
select new
{
time = element.Attribute("TIMING").Value,
enable = element.Attribute("ENABLED").Value
}).FirstOrDefault();
}
catch { return null; }
}
或者你有元组选项
public static Tuple<X,Y> GetWaveAnimation()
{
try
{
return (from element in configurations.Elements("Animation")
where element.Attribute("NAME").Value == "Wave"
select Tuple.Create(
element.Attribute("TIMING").Value,
element.Attribute("ENABLED").Value
)
}).FirstOrDefault();
}
catch { return null; }
}
关于c# - C#匿名类型声明,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5258240/