view datagear/dg/DataGear.cs @ 3:f27db91a852e

update MessagePackDagaGear.cs
author riono <e165729@ie.u-ryukyu.ac.jp>
date Tue, 23 Jun 2020 16:03:32 +0900
parents 740b80680d75
children e6f5b7d14dd1
line wrap: on
line source

using System;

namespace Christie_net.datagear.dg {
    public class DataGear<T> {
        protected T data;
        protected Type clazz = null;

        public DataGear(T data) {
            SetClazz(data.GetType());
            SetData(data);
        }

        public DataGear(Type clazz) {
            SetClazz(clazz);
        }

        public void SetData(T data) {
            Type dataClazz = data.GetType();

            if (dataClazz == this.clazz) {
                this.data = data;
                return;
            }

            Type dataSuperClazz = dataClazz.BaseType;
            while (dataSuperClazz != null) {
                if (dataClazz == this.clazz) {
                    this.data = data;
                    return;
                }
                dataSuperClazz = dataSuperClazz.BaseType;
            }
            
            Type[] interfaces = dataClazz.GetInterfaces();
            foreach (Type interfaze in interfaces) {
                if (interfaze == this.clazz) {
                    this.data = data;
                    return;
                }
            }
            
            throw new InvalidCastException("datagear cannot set class from" + dataClazz.GetType().Name + " to " + data.GetType().Name);
        }

        public void SetClazz(Type clazz) {
            this.clazz = clazz;
        }

        public Type GetClazz() {
            return clazz;
        }

        public T GetData() {
            return data;
        }

        public override string ToString() {
            return "DataGear : classname " + clazz;
        }
    }
}