mardi 5 février 2019

value.GetType().IsSubClassOf(ClassBase) give me the error of "'ClassBase' is a type, which is not valid in the given context"

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
    {

    }
}





Aucun commentaire:

Enregistrer un commentaire