C#匿名类型声明

时间:2011-03-10 10:17:05

标签: c# anonymous-types var

我有一个静态类,其方法使用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();
}

3 个答案:

答案 0 :(得分:1)

如果您需要静态类型(和命名)解决方案,应该创建一个单独的类。 有一些避免它的黑客方法,但一般来说这不是一个好主意。

如果您使用的是.NET 4,则另一个选择是返回IEnumerable<Tuple<string, string>>。这样您就会丢失“时间”和“已启用”的名称,但请注意它是一对字符串。

答案 1 :(得分:1)

另一个解决方案:Hidden Features of C#?

// Useful? probably not.
private void foo()
{
    var user = AnonCast(GetUserTuple(), new { Name = default(string), Badges = default(int) });
    Console.WriteLine("Name: {0} Badges: {1}", user.Name, user.Badges);
}

object GetUserTuple()
{
    return new { Name = "dp", Badges = 5 };
}    

// Using the magic of Type Inference...
static T AnonCast<T>(object obj, T type)
{
   return (T) obj;
}

答案 2 :(得分:0)

对于 .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 ,您可以使用动态关键字(但是您无法从程序集或朋友程序集外部调用此方法,因为匿名类型是内部的。)

 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; }
        }