当前位置:网站首页>C generic constraint

C generic constraint

2022-06-09 06:01:00 Go_ Accepted

1、 Generic constraint

Let the types of generics have certain restrictions

keyword :where

Generic constraints have a total of 6 Kind of :

Value type where Generic letters :struct
Reference type where Generic letters :class
There is a parameterless public constructor where Generic letters :new()
A class itself or a derived class where Generic letters : Class name
Derived type of an interface ( Derived types can be classes or interfaces )where Generic letters : The interface name
Another generic type itself or a derived type where Generic letters : Another generic letter

2、 Explanation of generic constraints

List part , Unlisted similar

(1) Value type constraint

class Test<T> where T:struct{

    public T value;

    public void TestFun<K>(K v) where K:struct{

    }

}

(2) Reference type constraints

class Test<T> where T:class{

    public T value;

    public void TestFun<K>(K v) where K:class{

    }

}

(3) No public participation Construction constraints

class Test<T> where T:new(){

    public T value;

    public void TestFun<K>(K v) where K:new(){

    }

}

public Test2{
    //  If the public nonparametric construct of this class is overridden by an overload , Or the parameterless construct is declared as private, Will report a mistake 
    //  This class cannot be an abstract class 
}
Test<Test2> t = new Test<Test2>();

Test<int> t = new Test<int>();  //  The nonparametric construction of a structure is not overridden , All structs have parameterless constructors 

(4) Another generic constraint

class Test<T,U> where T:U{

    public T value;

    public void TestFun<K,V>(K k) where K :V{

    }

}

among T And U The same or T yes U Derived types of ,K similar

3、 Combination of constraints

class Test<T> where  T:class, new(){

}

But be careful

class Test<T> where  T : new(),class{

}

Will report a mistake , therefore new() Usually written at the end

4、 Multiple generics have constraints

Followed by space where, The same format

class Test<T,K> where  T:class, new() where K:struct{

}

5、 practice

Implement a singleton pattern base class with generics

// where T : new()  Because  instance = new T()  Make sure  T  Type must have a parameterless constructor , But this will cause the constructor of the class to be  public  Of 
class SingleBase<T> where T : new(){
    private static T instance = new T();

    public static T Instance {
        get {
            return instance;
        }
    }
}

class Test : SingleBase<Test> {
    public int value = 10;
}
原网站

版权声明
本文为[Go_ Accepted]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206090559147667.html