本文介绍了对象调用最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 可能已经问过这个问题,但我仍然对此感到困惑。假设我有一个名为A的类,它包含一些属性,一个初始化其属性的方法,一个保存对象的方法。 那么调用对象的save方法的最佳做法是什么? 这个 一个objA = 新 objA(); objA.Name = abc; objA.Address = xyz; objA.Save(); 或 一个objA = new objA(); objA.Name = abc; objA.InitializeProperties( abc, xyz); objA.Save() 并假设另一个名为B的类包含其他类对象作为私有属性。 当我调用B.Update时,执行以下方法。在这种情况下哪种做法更好? 公开 类 B { public string 名称{ get ; set ;} public string 地址{ get ; set ;} private OtherClass otherClassObject { get ; set ;} private void MappObject( ref OtherClass otherClassObject) { otherClassObject.Name = 此请将.Name; otherClassObject.Address = this .Address; } public void 更新() { this .MappObject( this .otherClassObject) otherClassObject.Update() ; } } 解决方案 我会选择第一种方式,或者创建一个构造函数: public A( string 名称, string address) { Name = name; 地址=地址; } ... 一个objbA = 新 objA( abc, xyz) ; objA.Save(); 第二种方法有冗余,应该避免。 第一种和第二种方法方法允许保存一个可能'未初始化'的对象。 我将按 OriginalGriff 建议的方式定义一个构造函数,以便将对象置于其初始状态创建。 第一种方法应该是一种很好的方法。根据你的说法,有一个名为A的类,提到了属性和方法。然后我可以通过 一个objA = new A() { Name = abc, Address = xyz }; objA.Save(); 或其他你可以 上述solution1方法。 Hi, may be this question already has been asked but I am still confused in this. Say I have a class named A which contains some properties, a method to initialize its property, a method to save the object.then what is best practise to call the save method of the object?thisA objA = new objA();objA.Name = "abc";objA.Address= "xyz";objA.Save();ORA objA = new objA();objA.Name = "abc";objA.InitializeProperties("abc", "xyz");objA.Save()and suppose another class named B which contains other class object as private property.When I call B.Update, the following method is executed. in this scenario which practice is better?public class B{ public string Name{get;set;} public string Address{get;set;} private OtherClass otherClassObject {get;set;} private void MappObject(ref OtherClass otherClassObject){otherClassObject.Name = this.Name;otherClassObject.Address= this.Address;}public void Update(){ this.MappObject(this.otherClassObject)otherClassObject.Update();}} 解决方案 I'd go with the first way, or create a constructor:public A(string name, string address) { Name = name; Address = address; }...A objbA = new objA("abc", "xyz");objA.Save();The second method has redundance and should be avoided.Both first and second method allow a possibly 'uninitialised' object to be saved.I would define a constructor the way OriginalGriff suggested, in order to put the object in a initialized state on its very creation.First approach should be a good approach.According to you say there is a class named A with mentioned properties and methods.Then i can initialize the object of that particular class byA objA = new A(){ Name="abc", Address="xyz"};objA.Save();or else you can go for the above solution1 approach. 这篇关于对象调用最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 09-03 07:57