C# 如何将类型限制为C中的特定类型子集#
C# 如何将类型限制为C中的特定类型子集#,c#,inheritance,reflection,types,syntax,C#,Inheritance,Reflection,Types,Syntax,type类型的变量可以包含任何类型。我需要的是一个变量,它只能包含继承特定类并实现特定接口的类型。如何指定这一点?我已尝试将变量声明为 Type: MyClass, IMyInterface theTypeVariable; 作为 Type<MyClass, IMyInterface> theTypeVariable; 键入类型变量; 但两者都不起作用 正确的方法是什么 比如说 class A {...} class B {...} interface IC {...}
type
类型的变量可以包含任何类型。我需要的是一个变量,它只能包含继承特定类并实现特定接口的类型。如何指定这一点?我已尝试将变量声明为
Type: MyClass, IMyInterface theTypeVariable;
作为
Type<MyClass, IMyInterface> theTypeVariable;
键入类型变量;
但两者都不起作用
正确的方法是什么
比如说
class A {...}
class B {...}
interface IC {...}
interface ID {...}
class E: B, IC {...}
class F: B, IC, ID {...}
class G: ID {...}
...
// This following line invalid actually,
// so it is pseudocode of a kind
// the syntactically and semantically correct form of this is the question
Type: B, IC theTypeVariable; // or Type<B, IC> theTypeVariable // perhaps
theTypeVariable = typeof(E); // This assignment is to be valid.
theTypeVariable = typeof(F); // This assignment is to be valid.
theTypeVariable = typeof(A); // This assignment is to be invalid.
theTypeVariable = typeof(B); // This assignment is to be invalid.
theTypeVariable = typeof(IC); // This assignment is to be invalid.
theTypeVariable = typeof(G); // This assignment is to be invalid.
A类{…}
B类{…}
接口IC{…}
接口ID{…}
E类:B,IC{…}
类别F:B,IC,ID{…}
类别G:ID{…}
...
//下面这一行实际上是无效的,
//所以它是一种伪代码
//这个问题在语法和语义上都是正确的
类型:B,IC类型变量;//或者键入typevariable//maybe
typevariable=typeof(E);//此作业必须有效。
typevariable=typeof(F);//此作业必须有效。
类型变量=类型(A);//此分配无效。
typevariable=typeof(B);//此分配无效。
typevariable=typeof(IC);//此分配无效。
typevariable=typeof(G);//此分配无效。
举一个更明确的例子:我可能想声明一个类型变量,该变量只能包含扩展List
并实现IDisposable
(可丢弃的Ts列表,而不是可丢弃的列表)的任何类型
例如,我将实现
DisposableList:List,IDisposable
和另一个DisposableList实现:List,IDisposable
类,我想要一个能够存储typeof(DisposableList)
和typeof(另一个DisposableList实现)
但不能存储typeof(Foo)
或typeof的变量(列表)
类型
包含有关类型的元数据;它是反射API的一部分。这是无效的:
Type x = 5;
Type y = "Hello Sailor!";
要使类型U
成为T
的子类型并实现接口I
,可以使用泛型:
... Foo<U>(...)
where U : T, I
{
U myvar;
}
…Foo(…)
你在哪里,我在哪里
{
U myvar;
}
可以通过以下方式创建新类型:
class MyType : MyClass, IMyInterface
{
private MyClass A;
private IMyInterface B;
private MyType(MyClass a, IMyInterface b)
{
A = a;
B = b;
}
public static MyType Create<U>(U x)
where U : MyClass, IMyInterface
{
return new MyType(x, x);
}
// Implementations of MyClass and IMyInterface
// which delegate to A and B.
}
classmytype:MyClass,IMyInterface
{
私家车A级;
私人界面B;
私有MyType(MyClass a,IMY接口b)
{
A=A;
B=B;
}
公共静态MyType创建(U x)
其中U:MyClass,IMyInterface
{
返回新的MyType(x,x);
}
//MyClass和IMyInterface的实现
//哪个委托给A和B。
}
现在,类型为
MyType
的变量是MyClass
和IMyInterface
的子类型,我相信这就是您要寻找的
public class EstentedList<Type> where Type:List<T>,IDisposable
{
}
public class estendedlist,其中类型:List,IDisposable
{
}
你可以用这个类作为变量的类型这里根本不清楚你在问什么。@DavidG好的,给我一点时间,我会添加一些例子。谢谢你的反馈。你是指泛型吗?所以不,你问的是不可能的,也不清楚你为什么要这样做。这对我来说有点像是一种气味。一种va类型变量可以包含任何类型值,就像Int32变量可以包含任何Int32值一样。在处理上没有区别。这如何阻止特定类型存储在
类型
变量中?