亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在類 C# 的方法中迭代“This”屬性

在類 C# 的方法中迭代“This”屬性

C#
aluckdog 2021-10-09 10:53:47
我一直在搜索,但對此沒有運氣,我試圖從數據庫中的表調用類中的方法,此方法調用另一個查找條目并填充對象的方法,但是我想將此對象傳遞給我的類實例 public class ProductCategory    {        public int ProductCategoryID { get; set; }        public string Name { get; set; }        public Guid rowguid { get; set; }        public DateTime ModifiedDate { get; set; }        public void FindItem<T1>(T1 id)        {            try            {                var obj = Activator.CreateInstance(this.GetType());                obj = Dal.ObjFind(obj, id); //this fill the object                 //i want something like                foreach properties in obj                this.propertie = obj.propertie            }            catch (Exception e)            {                throw e;            }        }    }以一種我可以調用該方法的方式ProductCategory test = new ProductCategory();test.Find(1);之后我的對象被加載,我真的很感激這方面的任何幫助,對于糟糕的英語或者如果我沒有解釋清楚
查看完整描述

2 回答

?
精慕HU

TA貢獻1845條經驗 獲得超8個贊

好的,我找到了一種方法來實現 Pac0 所說的反射,你可以做到這一點


public  void FindItem<T1>(T1 id)

        {

            try

            {


                var obj = this;

                // fill the object with the DB data

                obj = Dal.ObjFind(new Production.ProductCategory(), id);


                PropertyDescriptorCollection PropertyObj = 

                 TypeDescriptor.GetProperties(this);

                //iterating the properties in the instance of the class

                foreach (PropertyDescriptor prop in PropertyObj)

                {

                    //Get the value for each properties in the filled Obj

                    //and set that value for each properites in "this"

                    prop.SetValue (this,prop.GetValue(obj));

                }




            }

            catch (Exception e)

            {

                throw e;

            }


        }

通過這種方式,您可以像“test.FindItem(1)”一樣調用您的安裝程序,并且對象將被加載,謝謝!


查看完整回答
反對 回復 2021-10-09
?
繁華開滿天機

TA貢獻1816條經驗 獲得超4個贊

要在運行時獲取有關某個類 durig 運行時的信息,稱為 *reflection**(該術語應該可以幫助您進行搜索)

要獲取類型的所有屬性,您可以使用Type.GetProperties()。

也看看GetProperty。

有了這個,你應該能夠實現你想要的。

但是,我不相信這是最簡單的方法??赡苡腥藭氤龈玫姆椒▉斫鉀Q您的潛在問題。


查看完整回答
反對 回復 2021-10-09
  • 2 回答
  • 0 關注
  • 256 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號