Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 是否可以获取对象的属性和关联属性?_C#_Reflection_Collections_Properties_Attributes - Fatal编程技术网

C# 是否可以获取对象的属性和关联属性?

C# 是否可以获取对象的属性和关联属性?,c#,reflection,collections,properties,attributes,C#,Reflection,Collections,Properties,Attributes,是否可以将属性及其关联属性作为集合或属性集获取 我正在查看的对象的属性具有可在JSON.NET中使用的属性,我想了解它们都是什么。之后,我将尝试找出其中哪些不是空的 下面是一个示例对象: [JsonObject] public class Conditions { [JsonProperty("opened_since")] public DateTime? OpenedSince { get; set; } [JsonProper

是否可以将属性及其关联属性作为集合或属性集获取

我正在查看的对象的属性具有可在JSON.NET中使用的属性,我想了解它们都是什么。之后,我将尝试找出其中哪些不是空的

下面是一个示例对象:

[JsonObject]
    public class Conditions
    {
        [JsonProperty("opened_since")]
        public DateTime? OpenedSince { get; set; }
        [JsonProperty("added_until")]
        public DateTime? AddedUntil { get; set; }
        [JsonProperty("opened_until")]
        public DateTime? OpenedUntil { get; set; }
        [JsonProperty("archived_until")]
        public DateTime? ArchivedUntil { get; set;
    }
试试这个

public static Hashtable ConvertPropertiesAndValuesToHashtable(this object obj)
    {
        var ht = new Hashtable();

        // get all public static properties of obj type
        PropertyInfo[] propertyInfos =
            obj.GetType().GetProperties().Where(a => a.MemberType.Equals(MemberTypes.Property)).ToArray();
        // sort properties by name
        Array.Sort(propertyInfos, (propertyInfo1, propertyInfo2) => propertyInfo1.Name.CompareTo(propertyInfo2.Name));

        // write property names
        foreach (PropertyInfo propertyInfo in propertyInfos)
        {
            ht.Add(propertyInfo.Name,
                   propertyInfo.GetValue(obj, BindingFlags.Public, null, null, CultureInfo.CurrentCulture));
        }

        return ht;
    }

像这样的?如果我理解正确的话,您需要由属性修饰的类的所有属性。我不想包含JSON.NET引用,所以使用了
XmlText
属性

    [Test]
    public void dummy()
    {
        var conditions = new Conditions();

        var propertyInfos = conditions.GetType().GetProperties();
        propertyInfos.ForEach(x =>
            {
                var attrs = x.GetCustomAttributes(true);
                if (attrs.Any(p => p.GetType() == typeof(XmlTextAttribute)))
                {
                    Console.WriteLine("{0} {1}", x, attrs.Aggregate((o, o1) => string.Format("{0},{1}",o,o1)));
                }
            });
    }
这个班看起来像这样-

[XmlType]
public class Conditions
{
    [XmlText]
    public DateTime? OpenedSince { get; set; }

    [XmlText]
    public DateTime? AddedUntil { get; set; }

    [XmlText]
    public DateTime? OpenedUntil { get; set; }

    [XmlText]
    public DateTime? ArchivedUntil { get; set; }

    public string NotTobeListed { get; set; }
}
控制台输出:

System.Nullable`1[System.DateTime] OpenedSince System.Xml.Serialization.XmlTextAttribute
System.Nullable`1[System.DateTime] AddedUntil System.Xml.Serialization.XmlTextAttribute
System.Nullable`1[System.DateTime] OpenedUntil System.Xml.Serialization.XmlTextAttribute
System.Nullable`1[System.DateTime] ArchivedUntil System.Xml.Serialization.XmlTextAttribute

请注意,
NotToBeListed
没有显示。

我在阅读了Chris的上述答案后,找到了答案

我创建此函数是为了帮我完成它:

    public HastTable BuildRequestFromConditions(Conditions conditions)
    {
        var ht = new HashTable();
        var properties = conditions.GetType().GetProperties().Where(a => a.MemberType.Equals(MemberTypes.Property) && a.GetValue(conditions) != null);
        properties.ForEach(property => 
            {
                var attribute = property.GetCustomAttribute(typeof(JsonPropertyAttribute));
                var castAttribute = (JsonPropertyAttribute)attribute;

                ht.Add(castAttribute.PropertyName, property.GetValue(conditions));
            });
        return request;
    }

这将为您提供所有属性、它们的属性以及属性参数的值(注意,此解决方案假定您使用的是.net framework 4.5版):

输出:

Property: OpenedSince
        Attribute: JsonPropertyAttribute
                String: opened_since
Property: AddedUntil
        Attribute: JsonPropertyAttribute
                String: added_until
Property: OpenedUntil
        Attribute: JsonPropertyAttribute
                String: opened_until
Property: ArchivedUntil
        Attribute: JsonPropertyAttribute
                String: archived_until

你的意思是像
条件c;PropertiesInfo infos=c.GetType().GetProperties()?谢谢,但这并没有得到属性的属性。这应该不会太难,我已经用一种方法更新了我的答案。可能需要一些重构。仅供参考,如果属性设置为[JsonProperty(PropertyName=“opened_since”]
Property: OpenedSince
        Attribute: JsonPropertyAttribute
                String: opened_since
Property: AddedUntil
        Attribute: JsonPropertyAttribute
                String: added_until
Property: OpenedUntil
        Attribute: JsonPropertyAttribute
                String: opened_until
Property: ArchivedUntil
        Attribute: JsonPropertyAttribute
                String: archived_until