public class MyClass<T> where T : class
{
private MyOtherClass<T, U> variable where U : class;
... content ...
}
public class MyOtherClass<T, U> where T : class where U : class
{
... content ...
}
는 것을 어떻게 든 수 있습니까?
public class MyClass<T> where T : class
{
private MyOtherClass<T, U> variable where U : class;
... content ...
}
public class MyOtherClass<T, U> where T : class where U : class
{
... content ...
}
는 것을 어떻게 든 수 있습니까?
당신의 필드 또는 속성의 유형을 확인하려면 MyClass
일반적인 몇 가지 유형 매개 변수 U
에 따라, 당신은 MyClass
의 유형 매개 변수로 선언해야한다 : 그러나
public class MyClass<T, U>
where T : class
where U : class
{
private MyOtherClass<T, U> variable;
... content ...
}
public class MyOtherClass<T, U>
where T : class
where U : class
{
... content ...
}
, 즉 '아무튼 메소드에 적용하지 마라. 이 완벽하게 괜찮 :
public class MyClass<T>
where T : class
{
private MyOtherClass<T, U> Method<U>() where U : class
{
... content ...
}
}
직접 제목은, 당신이 할 수없는 질문에 대답하려면 그 variable
는 MyOtherClass
가 유형의 매개 변수를 정의 의미 유형 MyOtherClass<T, U>
의 필드 때문에 T
및 U
- 네가 가진대로! 때문에 제네릭 형식 자체에 속한 제네릭 형식 제약의 선언 아니라 그것을 사용 유형에
MyClass<T>
의 T
가 아닌 MyOtherClass<T, U>
와 동일한 T
, - 그것은 좋은!
것이 가능했다, 이와 같은 유형 :
public class SomeRepository<TEntity>
where TEntity : IEntity { /* ... */}
아마도 다음과 같이 사용 될 수 있습니다 : 즉 정의 할 수 있습니다 (
public class SomeService
{
private SomeRepository<TEntity> _someRepo where TEntity : INotAnEntity
}
인터페이스, 클래스 및 방법은 일반적인 될 수 있습니다 유형 제약); 필드와 속성은 사용할 수 없지만 일반적인 유형일 수 있습니다.
MyClass<T>
에 MyOtherClass<T, U>
에 대한 참조가 포함 된 것으로 보입니다. 여기에서 모두 T
이 일치하지만 어느 것이나 U
이 허용됩니다. 이 작업을 수행하려는 경우 일반 대답 U
매개 변수가 포함 된 메서드에서 사용자가 U
을 지정해야하므로 기존 답변이 도움이되지 않을 수 있습니다.
형식 매개 변수가있는 클래스 (특히 여러 매개 변수)는 이와 같은 상황을 지원하기 위해 보다 작은 문자를 상속/구현해야합니다. 예를 들어 지금
public interface IOtherThing<T> {
T Value1 { get; }
object Value2 { get; }
}
public class MyOtherClass<T, U> : IOtherThing<T> {
public T Value1 { get { ... } }
public U Value2 { get { ... } }
object IOtherThing<T>.Value2 { get { return Value2; } }
}
, MyClass<T>
는 MyOtherClass<T, U>
에 할당 될 수 IOtherThing<T>
같은 변수를 선언 할 수있다.
+1 그런 식으로는 질문을하지 못했습니다. 그게 OP가 의미 한 것이고, 좋은 추측이며 좋은 대답입니다! MyOtherClass를 상속함으로써,'T'는 두 유형 모두에서 같은 의미를가집니다 (컴파일 할 때 동일한 유형 제약이 필요합니다). –