码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-04-10 00:59:14      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

在项目中,对于相似的操作,要抽象出一个方法,比如充值:充值现金、充值积分、充值电子币,这时可以用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的类型。

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

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!