C# Generics won't allow Delegate Type Constraints

前端 未结 8 1236
别跟我提以往
别跟我提以往 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

    Yes it's possible in C# 7.3, Constraints family increased to include Enum, Delegate and unmanaged types. You can write this code without a problem:

    void M<D, E, T>(D d, E e, T* t) where D : Delegate where E : Enum where T : unmanaged
        {
    
        }
    

    From Docs:

    Beginning with C# 7.3, you can use the unmanaged constraint to specify that the type parameter must be a non-nullable unmanaged type. The unmanaged constraint enables you to write reusable routines to work with types that can be manipulated as blocks of memory

    Useful links:

    The future of C#, from Microsoft Build 2018

    What's new in C# 7.3?

    0 讨论(0)
  • 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<T>() where T: Delegate
        {
        }
    
        public void MethodWithEnumConstraint<T>() where T: struct, Enum
        {
        }
    }
    
    0 讨论(0)
提交回复
热议问题