C #에서 'T : class'는 무엇을 의미합니까?
C #에서 무엇을 where T : class
의미합니까?
즉.
public IList<T> DoThis<T>() where T : class
간단히 말해서 이것은 일반 매개 변수를 클래스 (또는 클래스, 인터페이스, 대리자 또는 배열 유형 일 수있는 참조 유형)로 제한합니다.
자세한 내용은이 MSDN 기사 를 참조 하십시오.
그것은이다 제네릭 형식 제약 조건 . 이 경우 제네릭 형식 T
은 참조 형식 (클래스, 인터페이스, 대리자 또는 배열 형식)이어야합니다.
의 유형 제약 조건 T
이므로 클래스 여야 함을 지정합니다.
이 where
절은 다음과 같은 다른 유형 제약 조건을 지정하는 데 사용할 수 있습니다.
where T : struct // T must be a struct
where T : new() // T must have a default parameterless constructor
where T : IComparable // T must implement the IComparable interface
자세한 내용은 where
조항 의 MSDN 페이지 또는 일반 매개 변수 제약 조건을 확인하십시오 .
이것은 참조 유형으로 제한 T
됩니다 . 값 유형 ( s 및 기본 유형 제외 ) 을 넣을 수 없습니다 .struct
string
그것은 T
일반 메소드가 사용될 때 사용되는 유형 이 클래스 여야 함을 의미합니다. 즉, int
또는double
// Valid:
var myStringList = DoThis<string>();
// Invalid - compile error
var myIntList = DoThis<int>();
where T: class
말 그대로 그 의미합니다 T has to be a class
. 모든 참조 유형이 될 수 있습니다. 이제 코드가 DoThis<T>()
메소드를 호출 할 때마다 T 를 대체 할 클래스를 제공해야합니다 . 예를 들어 DoThis<T>()
메소드를 호출하려면 다음과 같이 호출해야합니다.
DoThis<MyClass>();
당신의 방법이 다음과 같다면 :
public IList<T> DoThis<T>() where T : class
{
T variablename = new T();
// other uses of T as a type
}
그런 다음 메소드에 T가 나타나면 MyClass로 바뀝니다. 따라서 컴파일러가 호출하는 최종 메소드는 다음과 같습니다.
public IList<MyClass> DoThis<MyClass>()
{
MyClass variablename= new MyClass();
//other uses of MyClass as a type
// all occurences of T will similarly be replace by MyClass
}
It is called a type parameter constraint. Effectively it constraints what type T can be.
The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.
Constraints on Type Parameters (C# Programming Guide)
T represents an object type of, it implies that you can give any type of. IList : if IList s=new IList; Now s.add("Always accept string.").
Here T refers to a Class.It can be a reference type.
'T' represents a generic type. It means it can accept any type of class. The following article might help:
http://www.15seconds.com/issue/031024.htm
참고URL : https://stackoverflow.com/questions/3786774/in-c-sharp-what-does-where-t-class-mean
'programing tip' 카테고리의 다른 글
git update-index --skip-worktree 실행 취소 (0) | 2020.07.10 |
---|---|
iPhone에서 NSString에 대한 AES 암호화 (0) | 2020.07.10 |
선택적 매개 변수를 함수에 전달하는 방법이 있습니까? (0) | 2020.07.10 |
안드로이드 아카이브 라이브러리 (ar) vs 표준 jar (0) | 2020.07.10 |
정확히 파이썬의 file.flush ()가 무엇을하고 있습니까? (0) | 2020.07.10 |