具有自定义属性和GetCustomAttributes的Bizarre行为

问题描述 投票:2回答:1

我已经为这个问题解决了好几个小时,但我找不到与SO(或Google)有关的任何东西。

这是我的问题:我有一个包含对象数组属性的自定义属性。

[System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = false)]
public class Property : System.Attribute
{
    public object[] Parameters { get; set; }

    public JsonProperty(object[] prms = null)
    {
        Parameters = prms;
    }
}

然后,我使用以下代码从属性中读取它:

var customProperties = (Property[])currentProperty.GetCustomAttributes(typeof(Property), false);

这对以下各项均适用:

[Property(Parameters = new object[]{}]
<...property...>

但是,如果将其设置为null ([Property(Parameters = null]),则会出现此错误:

System.Reflection.CustomAttributeFormatException:
'Parameters' property specified was not found.

这很荒谬,因为该属性是在我的自定义属性中定义的。我真的不明白。

所以我的问题是:怎么回事?

-编辑

如果将属性的类型从object []更改为object,则分配null很好。

-编辑以添加代码

属性:

[System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = false)]
public class JsonProperty : System.Attribute
{
    public object[] Parameters { get; set; }

    public JsonProperty(object[] prms = null)
    {
        Parameters = prms;
    }
}

Class:

public class MyClass
{
    [JsonProperty(Parameters = null)]
    public DateTime Start { get; set; }
}

方法:

public string getAttributes()
{
    Type t = MyClass.GetType();

     // Get only public properties and that have been set.
     var properties = t.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                       .Where(prop => prop.GetValue(this, null) != null);

     foreach (var prop in properties)
     {
          //The error occur on the next line.
          var jsonProperties =
              (JsonProperty[])prop.GetCustomAttributes(typeof(JsonProperty), false);

-如果您听不懂,请尝试阅读以下内容:

https://social.msdn.microsoft.com/Forums/vstudio/en-US/ddebbec6-1653-4502-9802-0b421efec60d/an-unexplicable-customattributeformatexception-from-getcustomattributes?forum=csharpgeneral

我也在那边问了这个问题。

我已经为这个问题解决了好几个小时,但我找不到与SO(或Google)有关的任何信息。这是我的问题:我有一个包含对象数组属性的自定义属性。 ...

c# custom-attributes getcustomattributes
1个回答
0
投票

我知道旧帖子,但是有一种解决方法。使用反射和自定义属性时,我遇到了类似的问题。我更改了属性以更新设置值(如果它为Null,如下所示)。

© www.soinside.com 2019 - 2024. All rights reserved.