Nice programing

무엇을

nicepro 2020. 10. 14. 20:57
반응형

무엇을 C #으로 표시


이 질문에 이미 답변이 있습니다.

저는 C #을 처음 접했고 제가받은 프로젝트의 일부 코드를 직접 수정했습니다. 그러나 다음과 같은 코드가 계속 표시됩니다.

class SampleCollection<T>

그리고 나는 무엇을 이해할 수 없습니다

<T> 

의미도 불린다.

이 개념이 무엇인지 이름 만 알려 주시면 온라인에서 검색 할 수 있습니다. 하지만 지금은 잘 모르겠습니다.


그것은이다 제네릭 형식 매개 변수 .

제네릭 형식 매개 변수를 사용하면 메서드 또는 클래스 선언에 구체적인 형식을 지정하지 않고도 컴파일시 메서드에 임의 형식 T를 지정할 수 있습니다.

예를 들면 :

public T[] Reverse<T>(T[] array)
{
    var result = new T[array.Length];
    int j=0;
    for(int i=array.Length - 1; i>= 0; i--)
    {
        result[j] = array[i];
        j++;
    }
    return result;
}

배열의 요소를 반전합니다. 여기서 요점은 배열 요소가 모든 유형이 될 수 있으며 함수가 계속 작동한다는 것입니다. 메소드 호출에서 유형을 지정합니다. 유형 안전성은 여전히 ​​보장됩니다.

따라서 문자열 배열을 반대로하려면 :

string[] array = new string[] { "1", "2", "3", "4", "5" };
var result = reverse(array);

문자열 배열 생산할 예정 result의를{ "5", "4", "3", "2", "1" }

이것은 다음과 같은 일반 (비 제네릭) 메서드를 호출 한 것과 동일한 효과를 갖습니다.

public string[] Reverse(string[] array)
{
    var result = new string[array.Length];
    int j=0;
    for(int i=array.Length - 1; i >= 0; i--)
    {
        result[j] = array[i];
        j++;
    }
    return result;
}

컴파일러는 array문자열 포함 된 것을 확인 하므로 문자열 배열을 반환합니다. 유형 매개 변수 string유형 으로 대체 T됩니다.


일반 유형 매개 변수를 사용하여 일반 클래스를 작성할 수도 있습니다. 당신이의 준 예에서 SampleCollection<T>의이 T임의의 유형에 대한 자리 표시 자입니다; SampleCollection, 컬렉션을 만들 때 지정하는 유형 인 개체 컬렉션을 나타낼 수 있습니다.

그래서:

var collection = new SampleCollection<string>();

문자열을 저장할 수있는 컬렉션을 만듭니다. Reverse약간 다른 형태로, 상기 예시에있어서, 집합의 구성원을 반전 할 수있다.


일반 유형 매개 변수 입니다. Generics 문서를 참조하십시오 .

T예약 된 키워드가 아닙니다. T, 또는 임의의 주어진 이름은 , 타입 파라미터를 의미한다. 다음 방법을 확인하십시오 (단순한 예).

T GetDefault<T>()
{
    return default(T);
}

반환 유형은 T입니다. 이 메서드를 사용하면 메서드를 다음과 같이 호출하여 모든 유형의 기본값을 가져올 수 있습니다.

GetDefault<int>(); // 0
GetDefault<string>(); // null
GetDefault<DateTime>(); // 01/01/0001 00:00:00
GetDefault<TimeSpan>(); // 00:00:00

.NET은 컬렉션에서 제네릭을 사용합니다. 예 :

List<int> integerList = new List<int>();

이렇게하면 클래스가 유형 ( T이 경우 int)으로 실행되고 요소를 추가하는 메서드가 다음과 같이 작성 되기 때문에 정수만 허용하는 목록을 갖게 됩니다.

public class List<T> : ...
{
    public void Add(T item);
}

제네릭에 대한 추가 정보.

유형의 범위를 제한 할 수 있습니다 T.

다음 예제에서는 클래스 인 유형으로 만 메소드를 호출 할 수 있습니다.

void Foo<T>(T item) where T: class
{
}

다음 예제에서는 Circle상속되었거나 상속 된 유형으로 만 메소드를 호출 할 수 있습니다 .

void Foo<T>(T item) where T: Circle
{
}

And there is new() that says you can create an instance of T if it has a parameterless constructor. In the following example T will be treated as Circle, you get intellisense...

void Foo<T>(T item) where T: Circle, new()
{
    T newCircle = new T();
}

As T is a type parameter, you can get the object Type from it. With the Type you can use reflection...

void Foo<T>(T item) where T: class
{
    Type type = typeof(T);
}

As a more complex example, check the signature of ToDictionary or any other Linq method.

public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);

There isn't a T, however there is TKey and TSource. It is recommended that you always name type parameters with the prefix T as shown above.

You could name TSomethingFoo if you want to.


This feature is known as generics. http://msdn.microsoft.com/en-us/library/512aeb7t(v=vs.100).aspx

An example of this is to make a collection of items of a specific type.

class MyArray<T>
{
    T[] array = new T[10];

    public T GetItem(int index)
    {
        return array[index];
    }
}

In your code, you could then do something like this:

MyArray<int> = new MyArray<int>();

In this case, T[] array would work like int[] array, and public T GetItem would work like public int GetItem.

참고URL : https://stackoverflow.com/questions/9857180/what-does-t-denote-in-c-sharp

반응형