program story

제네릭 유형과 함께 'using alias = class'를 사용하십니까?

inputbox 2020. 9. 8. 07:57
반응형

제네릭 유형과 함께 'using alias = class'를 사용하십니까? [복제]


그래서 때로는 전체 네임 스페이스가 아닌 네임 스페이스에서 하나의 클래스 만 포함하고 싶습니다. 여기 예제와 같이 using 문을 사용하여 해당 클래스에 대한 별칭을 만듭니다.

using System;
using System.Text;
using Array = System.Collections.ArrayList;

나는 종종 제네릭으로 이것을 수행하여 인수를 반복 할 필요가 없습니다.

using LookupDictionary = System.Collections.Generic.Dictionary<string, int>;

이제 제네릭 형식으로 유지하면서 제네릭 형식으로 동일한 작업을 수행하고 싶습니다.

using List<T> = System.Collections.Generic.List<T>;

그러나 그것은 컴파일되지 않으므로 유형을 제네릭으로 남겨 두면서이 별칭을 만드는 방법이 있습니까?


아니 없어. C #의 형식 별칭은 닫힌 (완전히 확인 된) 형식이어야하므로 개방형 제네릭이 지원되지 않습니다.

이 내용은 C # 언어 사양의 섹션 9.4.1에서 다룹니다.

별칭을 사용하면 닫힌 생성 형식의 이름을 지정할 수 있지만 형식 인수를 제공하지 않으면 바인딩되지 않은 제네릭 형식 선언의 이름을 지정할 수 없습니다 .

namespace N2
{
    using W = N1.A;         // Error, cannot name unbound generic type
    using X = N1.A.B;       // Error, cannot name unbound generic type
    using Y = N1.A<int>;    // Ok, can name closed constructed type
    using Z<T> = N1.A<T>;   // Error, using alias cannot have type parameters
}

그림과 같이 http://msdn.microsoft.com/en-us/library/sf0df423.aspxhttp://msdn.microsoft.com/en-us/library/c3ay4x3d%28VS.80%29.aspx , 당신 할수있다

using gen = System.Collections.Generic;
using GenList = System.Collections.Generic.List<int>;

그런 다음

gen::List<int> x = new gen::List<int>;

또는

GenList x = new GenList();

그러나 정의를 사용하는 모든 파일에서 정의를 사용하여 복제해야하므로 나중에 일부를 변경하고 모든 파일에서 업데이트하는 것을 잊으면 상황이 나빠질 것입니다.

I hope C# in the future Will treat aliases like the do with extension methods and let you define many of them in a file that you use elsewhere, then maintain them at one place and hide the internal unnecessary type mapping details from the type consumers.

참고URL : https://stackoverflow.com/questions/4936941/using-a-using-alias-class-with-generic-types

반응형