Programing

C # Generics에서 "기본"형식 매개 변수에 대한 합리적인 접근 방식이 있습니까?

lottogame 2020. 10. 15. 07:19
반응형

C # Generics에서 "기본"형식 매개 변수에 대한 합리적인 접근 방식이 있습니까?


C ++ 템플릿에서 특정 유형 매개 변수가 기본값임을 지정할 수 있습니다. 즉, 명시 적으로 지정하지 않는 한 유형 T를 사용합니다.

C #에서이 작업을 수행하거나 근사화 할 수 있습니까?

다음과 같은 것을 찾고 있습니다.

public class MyTemplate<T1, T2=string> {}

따라서 명시 적으로 지정하지 않는 유형의 인스턴스는 다음과 T2같습니다.

MyTemplate<int> t = new MyTemplate<int>();

본질적으로 다음과 같습니다.

MyTemplate<int, string> t = new MyTemplate<int, string>();

궁극적으로 상당히 널리 사용되는 템플릿이있는 경우를보고 있지만 추가 유형 매개 변수로 확장을 고려하고 있습니다. 나는 하위 클래스를 가질 수 있지만,이 맥락에서 다른 옵션이 있는지 궁금했습니다.


서브 클래 싱이 최선의 선택입니다.

주요 일반 클래스를 하위 클래스로 지정합니다.

class BaseGeneric<T,U>

특정 클래스

class MyGeneric<T> : BaseGeneric<T, string>

이렇게하면 논리를 한 위치 (기본 클래스)에 쉽게 보관할 수 있지만 두 가지 사용 옵션을 모두 쉽게 제공 할 수 있습니다. 수업에 따라이를 수행하는 데 필요한 추가 작업이 거의 없을 것입니다.


한 가지 해결책은 서브 클래 싱입니다. 대신 사용할 또 다른 방법은 팩토리 메서드 (var 키워드와 결합)입니다.

public class MyTemplate<T1,T2>
{
     public MyTemplate(..args..) { ... } // constructor
}

public static class MyTemplate{

     public static MyTemplate<T1,T2> Create<T1,T2>(..args..)
     {
         return new MyTemplate<T1, T2>(... params ...);
     }

     public static MyTemplate<T1, string> Create<T1>(...args...)
     {
         return new MyTemplate<T1, string>(... params ...);
     }
}

var val1 = MyTemplate.Create<int,decimal>();
var val2 = MyTemplate.Create<int>();

위의 예에서 val2형인 MyTemplate<int,string> 아니라 이로부터 파생 된 타입.

유형 class MyStringTemplate<T>:MyTemplate<T,string>이와 같은 유형 이 아닙니다 MyTemplate<T,string>. 이로 인해 특정 시나리오에서 몇 가지 문제가 발생할 수 있습니다. 예를 들어의 인스턴스 MyTemplate<T,string>MyStringTemplate<T>.


다음과 같이 클래스 오버로드를 만들 수도 있습니다.

public class MyTemplate<T1, T2> {
    public T1 Prop1 { get; set; }
    public T2 Prop2 { get; set; }
}

public class MyTemplate<T1> : MyTemplate<T1, string>{}

C #은 이러한 기능을 지원하지 않습니다.

말했듯이 (봉인되지 않은 경우 모든 생성자 선언을 복제) 하위 클래스를 만들 수 있지만 완전히 다른 것입니다.


Unfortunately C# does not support what you are trying to do. It would be a difficult feature to implement given that the default type for a parameter would have to adhere to the generic constraints and would most likely create headaches when the CLR tried to ensure type-safety.

참고URL : https://stackoverflow.com/questions/707780/is-there-a-reasonable-approach-to-default-type-parameters-in-c-sharp-generics

반응형