我希望变量只包含继承特定抽象的类的类型。在此示例中,变量“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);
答案 0 :(得分:3)
在这种情况下,您需要使用数据类型LetterAbstract
(所谓的基类)声明变量。
LetterAbstract letter;
letter = new LetterA(); // valid
letter = "asdasd"; // invalid
我认为您首先需要阅读有关继承的内容,请参阅" Inheritance (C# Programming Guide)"。
:编辑
关于
我不想要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
答案 1 :(得分:0)
我不想要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
答案 2 :(得分:0)
您是否考虑过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));