named parameter type constraints

后端 未结 5 2051

I am designing a custom attribute class.

public class MyAttr: Attribute
{
    public ValueRange ValRange { get; set; }
}

Then I am attempti

5条回答
  •  Happy的楠姐
    2020-12-07 02:45

    Is there any way around this?

    Yes.

    You can have your attribute use a Type property and then use types that implement a defined interface, for which the code that processes that attribute would have to assume, and as such also create an implicit, but hopefully documented, requirement to its clients:

    public interface IValueRange {
      int Start { get; }
      int End { get; }
    }
    public class MyAttr : Attribute { 
      // The used type must implement IValueRange
      public Type ValueRangeType { get; set; } 
    }
    
    // ....
    
    public class Foo { 
    
      class FooValueRange : IValueRange {
        public int Start { get { return 10; } }
        public int End { get { return 20; } }
      }
      [MyAttr(ValueRangeType = typeof(FooValueRange))]
      public string Prop { get; set; }
    
    }
    

    This is not unlike many classes in the System.ComponentModel namespace, like DesignerAttribute.

提交回复
热议问题