猿问

在类 C# 的方法中迭代“This”属性

我一直在搜索,但对此没有运气,我试图从数据库中的表调用类中的方法,此方法调用另一个查找条目并填充对象的方法,但是我想将此对象传递给我的类实例


 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);

之后我的对象被加载,我真的很感激这方面的任何帮助,对于糟糕的英语或者如果我没有解释清楚



aluckdog
浏览 231回答 2
2回答

精慕HU

好的,我找到了一种方法来实现 Pac0 所说的反射,你可以做到这一点public&nbsp; void FindItem<T1>(T1 id)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var obj = this;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // fill the object with the DB data&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; obj = Dal.ObjFind(new Production.ProductCategory(), id);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; PropertyDescriptorCollection PropertyObj =&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;TypeDescriptor.GetProperties(this);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //iterating the properties in the instance of the class&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; foreach (PropertyDescriptor prop in PropertyObj)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //Get the value for each properties in the filled Obj&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //and set that value for each properites in "this"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; prop.SetValue (this,prop.GetValue(obj));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; catch (Exception e)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw e;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }通过这种方式,您可以像“test.FindItem(1)”一样调用您的安装程序,并且对象将被加载,谢谢!

繁华开满天机

要在运行时获取有关某个类 durig 运行时的信息,称为 *reflection**(该术语应该可以帮助您进行搜索)要获取类型的所有属性,您可以使用Type.GetProperties()。也看看GetProperty。有了这个,你应该能够实现你想要的。但是,我不相信这是最简单的方法。可能有人会想出更好的方法来解决您的潜在问题。
随时随地看视频慕课网APP
我要回答