获取阅读匿名类型

获取阅读匿名类型

本文介绍了获取阅读匿名类型/写性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取可写入匿名类型的所有属性。

I need to fetch all the properties of an anonymous type which can be written to.

例如:

 var person = new {Name = "Person's Name", Age = 25};
 Type anonymousType = person.GetType();
 var properties = anonymousType.GetProperties(BindingFlags.Public | BindingFlags.Instance);



现在的问题是,所有的属性都有自己的 CanWrite 属性。这是返回真正的非匿名类型。结果
我也尝试拨打电话,以 PropertyInfo.GetSetMethod()返回结果
我如何检查属性是否可以写入

The problem is that all the properties have their CanWrite property false. This is returned as true for non anonymous types.
I have also tried making a call to PropertyInfo.GetSetMethod() which returns null.
How can I check whether the property can be written to?

编辑:
也许就足以知道,如果一个类型是匿名与否。如何才能知道如果一个类型使用反射是匿名的?

Perhaps it would suffice to know if a type is anonymous or not. How do I find out if a type is anonymous using reflection?

推荐答案

在C#中产生的匿名类型的总是不变的,所以设置可写的属性是空的。在VB中它是可选的:每个属性的默认的到是可变的,但如果你用关键字前缀它这是不可改变的;只有使用性质计数平等和哈希代码生成声明。我个人更喜欢C#的方法。

Anonymous types generated from C# are always immutable, so the set of writable properties is empty. In VB it's optional: each property defaults to being mutable, but if you prefix it with Key it's immutable; only properties declared using Key count for equality and hash code generation. Personally I prefer C#'s approach.

CanWrite 不是的总是的返回为真在非匿名类型的属性 - 仅适用于可写的。属性可以是只读,只写,或读写。例如:

CanWrite isn't always returned as true for properties in non-anonymous types - only for writable ones. Properties can be read-only, write-only, or read-write. For example:

public class Test
{
    // CanWrite will return false. CanRead will return true.
    public int ReadOnly { get { return 10; } }

    // CanWrite will return true. CanRead will return false.
    public int WriteOnly { set {} }

    // CanWrite will return true. CanRead will return true.
    public int ReadWrite { get { return 10; } set {} }
}

这篇关于获取阅读匿名类型/写性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 19:46