对方法传入对象,根据对象的Type选择不同的方法;typeof() 和 GetType()的区别

在项目中,对于相似的操作,要抽象出一个方法,比如充值:充值现金、充值积分、充值电子币,这时可以用Object传入参数,用.GetType().Name获得参数到底是什么类型。

代码

        public static bool RechargeServiceCenter(ServiceCenterRechargeView serviceCenterRechargeView, Object SCRechargeRecord)
        {
            using (DataBaseEntities db = new DataBaseEntities())
            {
                //充值记录:电子币
                if (SCRechargeRecord.GetType().Name == "tbServiceCenterRechargeRecord")
                {
                    tbServiceCenterRechargeRecord record = (tbServiceCenterRechargeRecord)SCRechargeRecord;
                    db.tbServiceCenterRechargeRecord.Add(record);

                }
                //充值记录:现金
                else
                {
                    tbServiceCenterRechargeRecord_CashMoney record = (tbServiceCenterRechargeRecord_CashMoney)SCRechargeRecord;
                    db.tbServiceCenterRechargeRecord_CashMoney.Add(record);
                }

注意:typeof() 和 GetType()是有区别的,

1、typeof(x)中的x,必须是具体的类名、类型名称等,不可以是变量名称。 
2、GetType()方法继承自Object,所以C#中任何对象都具有GetType()方法,它的作用和typeof()相同,返回Type类型的当前对象的类型。

比如有这样一个变量i:
Int32 i = new Int32();

i.GetType()返回值是Int32的类型,但是无法使用typeof(i),因为i是一个变量,如果要使用typeof(),则只能:typeof(Int32),返回的同样是Int32的类型。

反射 介绍System.Type类

原文地址:https://www.cnblogs.com/tider1999/p/4412994.html