![](/img/trans.png)
[英]How can I declare an abstract generic class that inherits from another abstract class?
[英]How do I make a variable that requires a type of a class that inherits an abstract?
我希望变量只包含继承特定抽象的类的类型。 在此示例中,变量“MyLetter”应该只包含LetterA,LetterB或继承LetterAbstract的任何类型。
我怎么做到这一点?
abstract class LetterAbstract
{
public char Letter;
}
class LetterA : LetterAbstract
{
void LetterA()
{
Letter = 'A';
}
}
// valid
TLetterAbstract MyLetter = typeof(LetterA);
// invalid
TLetterAbstract MyLetter = typeof(string);
在这种情况下,您需要使用数据类型LetterAbstract
(所谓的基类)声明变量。
LetterAbstract letter;
letter = new LetterA(); // valid
letter = "asdasd"; // invalid
我想你首先需要阅读有关继承的内容,参见“ 继承(C#编程指南) ”。
:编辑
关于
我不想要LetterA的实例。 我想要类型LetterA。
你可以用泛型来捣乱一些东西,但我不知道用例可能是什么:
class TypeVar<A>
where A: LetterAbstract
{
public void SetValue<B>()
where B: A
{
mValue = typeof(B);
}
public System.Type GetValue()
{
return mValue;
}
private System.Type mValue;
}
var x =new TypeVar<LetterAbstract>();
x.SetValue<LetterA>(); // valid
x.SetValue<string>(); // invalid
x.GetValue(); // get the type
我不想要LetterA的实例。 我想要类型LetterA
虽然你想要的东西对我来说似乎并不清楚。 尝试这个。
请注意,如果要限制编码,则除非您声明变量Letter
否则无法进行编码,但您可以确定变量是否是某种类型的子类。
static bool IsLetter(object obj)
{
Type type = obj.GetType();
return type.IsSubclassOf(typeof(Letter)) || type == typeof(Letter);
}
样品:
class Foo
{
}
abstract class Letter
{
}
class LetterA : Letter
{
}
class LetterAA : LetterA
{
}
class LetterAB : LetterA
{
}
用法:
LetterAA aa = new LetterAA();
LetterAB ab = new LetterAB();
Foo foo = new Foo();
bool isAA = IsLetter(aa);
bool isAB = IsLetter(ab);
bool isLetter = IsLetter(foo);
Console.WriteLine(isAA); // True
Console.WriteLine(isAB); // True
Console.WriteLine(isLetter); // False
您是否考虑过TLetterAbstract
类? 您可以将其定义为:
public class TLetterAbstract : Type
{
private Type _T;
public TLetterAbstract(object o)
{
if (o is LetterAbstract)
{
_T = o.GetType();
}
throw new ArgumentException("Wrong input type");
}
public TLetterAbstract(Type t)
{
if (t.IsInstanceOfType(typeof(LetterAbstract)))
{
_T = t;
}
throw new ArgumentException("Wrong input type");
}
public override object[] GetCustomAttributes(bool inherit)
{
return _T.GetCustomAttributes(inherit);
}
// and some more abstract members of Type implemented by simply forwarding to the instance
}
然后你必须改变你的代码
TLetterAbstract MyLetter = typeof(LetterA);
至
TLetterAbstract MyLetter = new TLetterAbstract(typeof(LetterA));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.