C# 从匿名类型获取值?

C# 从匿名类型获取值?,c#,anonymous-types,C#,Anonymous Types,假设我们有以下方法: public object Test() { return new { A = "Test" }; } 是否有可能获得存储在a中的值 var b = Test(); //Any chance to cast this to the anonymous type? 请注意,从方法返回匿名类型或元组是一件不好的事情 但是你问了一个关于如何做的问题,而不是关于“这是个好主意吗” 通过使用动态或反射 dynamic b = Test(); string str = b.

假设我们有以下方法:

public object Test()
{
    return new { A = "Test" };
}
是否有可能获得存储在a中的值

var b = Test(); //Any chance to cast this to the anonymous type?

请注意,从方法返回匿名类型或
元组是一件不好的事情

但是你问了一个关于如何做的问题,而不是关于“这是个好主意吗”

通过使用动态或反射

dynamic b = Test();
string str = b.A;
或者通过欺骗:

public static object Test()
{
    return new { A = "Test" };
}

public static string GetA(object obj)
{
    // We create an anonymous type of the same type of the one in Test()
    // just to have its type.
    var x = new { A = string.Empty };

    // We pass it to Cast, that will take its T from the type of x
    // and that will return obj casted to the type of the anonymous
    // type
    x = Cast(x, obj);

    // Now in x we have obj, but strongly typed. So x.A is the value we
    // want
    return x.A;
}

public static T Cast<T>(T type, object obj) where T : class
{
    return (T)obj;
}

string str = GetA(Test());
//有没有机会将其转换为匿名类型

是的,您可以使用cast by example

public static T CastByExample<T>(this object obj, T example) {
     return (T)obj;
}
或者,您可以使用
动态

dynamic b = Test();
Console.WriteLine(b.A);
或者,使用反射:

object b = Test();
var property = b.GetType().GetProperty("A");
var value = property.GetValue(b);
Console.WriteLine(value);
或者,您可以做正确的事情,创建一个标称(即非匿名)类型

有没有机会将其转换为匿名类型

虽然你可以这样做,但它是非常不可靠的。因为每当你改变你创建的匿名类型时,你的代码就会在其他地方突然中断,没有任何痕迹

你可以在Jon Skeet的博客中阅读所有扮演匿名类型的失败。马克·格拉斯的评论也值得一读

上述博客中讨论的打破变化的示例

using System;

static class GrottyHacks
{
    internal static T Cast<T>(object target, T example)
    {
        return (T) target;
    }
}

class CheesecakeFactory
{
    static object CreateCheesecake()
    {
        return new { Fruit="Strawberry", Topping="Chocolate" };
    }

    static void Main()
    {
        object weaklyTyped = CreateCheesecake();
        var stronglyTyped = GrottyHacks.Cast(weaklyTyped,
            new { Fruit="", Topping="" });

        Console.WriteLine("Cheesecake: {0} ({1})",
            stronglyTyped.Fruit, stronglyTyped.Topping);            
    }
}
那你的这条线会怎么样

var stronglyTyped = GrottyHacks.Cast(weaklyTyped,
            new { Fruit="", Topping="" });

它将不再工作。

匿名类型被设计为在创建它们的相同范围内使用。试图做到这一点就是将它用于它不是为之设计的东西,因此它作为一种技术是非常无效的;你应该避免把自己置于那种境地。
using System;

static class GrottyHacks
{
    internal static T Cast<T>(object target, T example)
    {
        return (T) target;
    }
}

class CheesecakeFactory
{
    static object CreateCheesecake()
    {
        return new { Fruit="Strawberry", Topping="Chocolate" };
    }

    static void Main()
    {
        object weaklyTyped = CreateCheesecake();
        var stronglyTyped = GrottyHacks.Cast(weaklyTyped,
            new { Fruit="", Topping="" });

        Console.WriteLine("Cheesecake: {0} ({1})",
            stronglyTyped.Fruit, stronglyTyped.Topping);            
    }
}
static object CreateCheesecake()
    {
        return new { Fruit="Strawberry", Topping="Chocolate", Base = "Biscuit" };
    }
var stronglyTyped = GrottyHacks.Cast(weaklyTyped,
            new { Fruit="", Topping="" });