4

私は何時間もこの問題と戦ってきましたが、SOに関連するものは何も見つかりませんでした(またはグーグルで)。

これが私の問題です: オブジェクト配列プロパティを含むカスタム属性があります。

[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;
    }
}

クラス:

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

私もそこで質問しました。

4

2 に答える 2