So am trying to check that a property is derived from a base class before storing it in the backing field. However I get the following syntax error 'ClassBase' is a type, which is not valid in the given context
for line value.IsSubclassOf(ClassBase)
which makes no sense since ClassBase is a Type and IsSubclassOf is expecting a type.
MCV example below
using System;
namespace QuestionIsSubClassOf
{
class Program
{
static void Main(string[] args)
{
var DataStorageClass = new DataStorageClass();
var DerivedClassA = new ClassDedrivedA();
DataStorageClass.TypeOfClassBase = DerivedClassA.GetType();
}
}
public class DataStorageClass
{
private Type _typeOfClassBase;
public Type TypeOfClassBase
{
get { return _typeOfClassBase; }
set
{
if (value.IsSubclassOf(ClassBase))
{
_typeOfClassBase = value.GetType();
}
else
{
throw new ArgumentOutOfRangeException($"{nameof(TypeOfClassBase)} must be a subclass of {nameof(ClassBase)}");
}
}
}
}
public class ClassBase
{
}
public class ClassDedrivedA : ClassBase
{
}
public class ClassDedrivedB : ClassBase
{
}
}
You need to use the typeof
operator in C#.
if (value.IsSubclassOf(typeof(ClassBase)))
{
_typeOfClassBase = value.GetType();
}
else
{
throw new ArgumentOutOfRangeException($"{nameof(TypeOfClassBase)} must be a subclass of {nameof(ClassBase)}");
}
The typeof
operator returns a Type
object which corresponds to the type it was passed as an argument. When you're working on an instance you may not necessarily know what that type is so typeof
cannot be used, which is why the GetType()
function exists on the object
class.
I'd also like to check if you mean to use IsSubclassOf
or whether you actually want to use IsInstanceOfType
/ IsAssignableFrom
.我也想检查,如果你的意思是使用IsSubclassOf
,还是你真的想使用IsInstanceOfType
/ IsAssignableFrom
。
IsSubclassOf
does not return true if you're comparing against the same type. Ie
typeof(Type1).IsSubclassOf(typeof(Type1)) //returns false
If you're always comparing instances against a base type then you can use IsInstanceOfType
, otherwise you can use IsSubclassOf
with an additional check for ==
. Alternatively their's IsAssignableFrom
but their may be caveats with that. I'd always advice reading the documentation - MSDN in this case.
EDIT 2021-03-14: I know this is an old question, but with newer versions of C# you can use pattern matching syntax which is much nicer.
// `is` will match for base and derived types
if(value is ClassBase)
_typeOfClassBase = value.GetType();
else
throw new ArgumentOutOfRangeException(...);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.