C# Generics won't allow Delegate Type Constraints

前端 未结 8 1279
别跟我提以往
别跟我提以往 2020-11-28 08:01

Is it possible to define a class in C# such that

class GenericCollection : SomeBaseCollection where T : Delegate

I couldn

8条回答
  •  悲哀的现实
    2020-11-28 08:35

    If you are willing to take a compile time dependency on an IL Weaver you can do this with Fody.

    Using this addin to Fody https://github.com/Fody/ExtraConstraints

    Your code can look like this

    public class Sample
    {
        public void MethodWithDelegateConstraint<[DelegateConstraint] T> ()
        {        
        }
        public void MethodWithEnumConstraint<[EnumConstraint] T>()
        {
        }
    } 
    

    And be compiled to this

    public class Sample
    {
        public void MethodWithDelegateConstraint() where T: Delegate
        {
        }
    
        public void MethodWithEnumConstraint() where T: struct, Enum
        {
        }
    }
    

提交回复
热议问题