获取动态类型的类类型?

发布于 2024-12-18 04:11:07 字数 304 浏览 2 评论 0原文

我写了一些代码:

    public static object func()
    {
        return new { a = 1, b = 2 };
    }

   Console.WriteLine((func() as dynamic).a); //returns '1'.

如果我可以这样做:func() as dynamic 所以动态应该是某种引用类型/类。

我寻找它的类类型但找不到任何(通过反射器)。

它的类型是什么? (参考类型)?

I wrote some code :

    public static object func()
    {
        return new { a = 1, b = 2 };
    }

   Console.WriteLine((func() as dynamic).a); //returns '1'.

If I can do : func() as dynamic so dynamic should be some kind of reference type / class.

I looked for its Class type but couldn't find any (via reflector).

what is its type ? ( reference type) ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

安人多梦 2024-12-25 04:11:07

您可以像平常一样通过 GetType() 获取类型。

这是一个匿名类型,它(作为实现细节)是泛型类型的一种形式。在 C# 中,类型的名称故意不发音。

如果您查看反射器,可能有一个以 '2 结尾的内部泛型类型(表示 2 个泛型类型参数),分别具有第一个和第二个泛型类型参数的两个属性“a”和“b”。它是一个类,因此是一个引用类型。

注意:

new { a = true, b = 123.45 }

实际上会使用相同的泛型类型,但具有不同的泛型类型参数。

还;使用dynamic不会改变对象——它只会改变它的访问方式。

You can get the type via GetType() as normal.

That is an anonymous type, which is (as an implementation detail) a form of generic type. The name of the type is deliberately unpronounceable in c#.

If you look in reflector, there is probably an internal generic type somewhere ending in ’2 (to indicate 2 generic type parameters), with two properties "a" and "b", of the first and second generic type arguments respectively. It is a class, so a reference-type.

As a note:

new { a = true, b = 123.45 }

Would actually use the same generic type but with different generic type parameters.

Also; using dynamic doesn't change the object - it only changes how it is accessed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文