【问题标题】:iterating "This" properties in a method of a class C#在 C# 类的方法中迭代“This”属性
【发布时间】:2018-12-23 11:26:16
【问题描述】:

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

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

然后我的对象被加载,我真的很感激任何帮助,对不起英语不好或者我解释不清楚

问候

【问题讨论】:

    标签: c# class methods instance


    【解决方案1】:

    好的,我找到了一种方法来实现 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)”一样调用你的instalce,然后对象就会被加载,谢谢!

    【讨论】:

    • 感谢您提供反馈和您自己的工作解决方案!顺便说一句,您可以将自己的答案标记为已接受。
    【解决方案2】:

    在运行时获取有关某个类 durig 运行时的信息称为 *reflection**(该术语应该可以帮助您进行搜索)

    要获取一个Type的所有属性,可以使用Type.GetProperties()

    也请查看GetProperty

    有了这个,你应该可以实现你想要的。

    但是,我不相信这是最简单的方法。可能有人会想出更好的方法来解决您的根本问题。

    【讨论】:

    • 我已经准备好使用反射但是这种情况是不同的,因为我想通过一个方法改变实例本身,我可以进行赋值 test=test.Find(1) 但这就是我的万避免
    • @V-mos 你可以通过反射完美地“改变实例本身”,所以我不确定我是否正确理解你的评论。
    • 经过一番思考,我宁愿使用一些接口,例如ICopyable&lt;T&gt;,并使用返回对象副本的方法,例如public T CreateCopy(T original),并为您需要获取的所有类实现它对象的副本,或使用基类和反射仅创建一个实现并使所有 db 类都继承自该基类。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-18
    相关资源
    最近更新 更多