泛型應用_函式會依照傳進來的物件參數來分別處理不同邏輯

函式會依照傳進來的物件來分別處理不同邏輯

reference:簡單介紹泛型(GenericClass)並實作一個範例  https://tinyurl.com/tp6ljnr

範例:

Billing\Controllers\BillDataUpdateController.cs & Billing\Controllers\VehicleDataUpdateImportController.cs

兩隻程式共用同一個方法 public bool DataCheck<T>(T t),要傳入不同的class進去當參數,從不同的class取得其成員做其他應用

實際應用:

DataUpdateModel.DataCheck<DataUpdateModel.ObjBillData>(dataModel)

function邏輯:

        public bool DataCheck<T>(T t)
        {
            string ID_NO = "";
            int VEHICLE_ID = 0;
            string LPR_NUMBER = "";

            MyGenericClass mg = new MyGenericClass();
            Type tp = t.GetType();//取得傳入參數class的名字
                if (tp.Name == "ObjBillData")
                {
                    mg.SetInstance<T>(t);
                    ObjBillData obj = mg.GetInstance<ObjBillData>();//泛型參數轉型成ObjBillData
                    ID_NO = obj.ID_NO;
                    VEHICLE_ID = obj.VEHICLE_ID;
                    LPR_NUMBER = obj.LPR_NUMBER;
                }
                else if (tp.Name == "ObjVehicleData")
                {
                    mg.SetInstance<T>(t);
                    ObjVehicleData obj = mg.GetInstance<ObjVehicleData>();//泛型參數轉型成ObjVehicleData
                    ID_NO = obj.ID_NO;
                    VEHICLE_ID = obj.VEHICLE_ID;
                    LPR_NUMBER = obj.LPR_NUMBER;             
                }

            bool res = false;
            var data = info.db.Database.SqlQuery<BMS_PRO_VEHICLE>(@"
                SELECT VEH.* FROM BMS_PRO_CONSUMER CON WITH(NOLOCK)
                INNER JOIN BMS_PRO_VEHICLE VEH WITH(NOLOCK) ON CON.CONSUMER_ID = VEH.OWNER_ID
                WHERE CON.ID_NO = @para_ID_NO AND VEH.VEHICLE_ID = @para_VEHICLE_ID AND VEH.LPR_NUMBER = @para_LPR_NUMBER
            ", new object[]{
                new SqlParameter("@para_ID_NO", ID_NO),
                new SqlParameter("@para_VEHICLE_ID", VEHICLE_ID),
                new SqlParameter("@para_LPR_NUMBER", LPR_NUMBER)
             }).FirstOrDefault();
            if (data != null)
            {
                res = true;
            }
            return res;
        }

泛型處理class 邏輯:

        public class MyGenericClass
        {
            private object aInstance;// 以實體物件儲放樣版物件,測試樣版物件與實體物件的互通性。
            public void SetInstance<T>(T t)
            {

                aInstance = t; // 以實體儲放樣版。

            }
            public T GetInstance<T>()
            {

                return (T)aInstance; // 自實體物件取回樣版物件。

            }
        }

物件ObjBillData

        public class ObjBillData
        {
            public string LPR_NUMBER { get; set; }
            public string ID_NO { get; set; }
            public int VEHICLE_ID { get; set; }
            public string MODIFY_TYPE { get; set; }
            public string NEW_DATA { get; set; }
        }