// new() .
Using System;
class MyClass {
public MyClass() {
//...
}
//...
}
class Test<T> where T: new() {
T obj;
public Test() {
// new(). obj = new (); //
}
//...
}
class ConsConstraintDemo {
static void Main() {
Test<MyClass> x = new Test<MyClass>();
}
}
Test.
class Test<T> where T: new() {
new () .
Test.
public Test () {
// new(). obj = new (); //
}
, obj. , new () . , new (), . .
Main () Test, .
Test<MyClass> = new Test<MyClass>();
, MyClass . , Test. , MyClass . . , , .
new (), . -, , . -, new () , , . , . -, new () , .
, , , , . , . .
where : class
where class , . , , int bool, .
|
|
.
where : struct
struct , . (, .) , , string, . , class struct .
, .
// .
Using System;
class MyClass {
//...
}
// , class Test<T> where : class {
obj;
public Test () {
// , // // , , obj = null;
}
//...
}
class ClassConstraintDemo { static void Main() {
// , MyClass . Test<MyClass> = new Test<MyClass>();
// , // int .
// Test<int> = new Test<int>();
}
}
Test, class Test<T> where T: class {
class , . Test.
public Test () {
// , // // , , obj = null;
}
obj . . , . ( , , (null). 20.) , , . , .
. , , , , struct enum. ( .) .
// .
Using System;
struct MyStruct {
//...
}
class MyClass {
//...
}
class Test<T> where T: struct {
T obj;
public Test(T x) { obj = x;
}
//...
}
class ValueConstraintDemo { static void Main() {
// .
Test<MyStruct> = new Test<MyStruct>(new MyStruct ());
|
|
Test<int> = new Test<int>(10);
// !
// Test<MyClass> z = new Test<MyClass>(new MyClass());
}
}