开发者

Returning data from one method to another within a class

Thanks for help with the question I just submitted about anonymous classes. Now I understand more. Here's a bit more of an example:

public class abc {
 public xx doAction() {
    return ( new { ID = 5, Name= "Dave" } );
 }
 public void doStart() {
    var a = doAction();
    var b = a.ID;
    var c = a.Name;
 }
}

So am I correct in saying that the most ideal way to do this would be to declare a class XYX and use it like this:

public class abc {
 public XYZ doAction() {
    return ( new XYZ { ID = 5, Name= "Dave" } );
 }
 public void doStart() {
    var a = doAction();
    var b = a.ID;
    var c = a.Name;
 }
}

The class would be only used fo开发者_开发问答r this one data transfer between the two methods.


I think you meant: return new XYZ(5, "Dave") Anyways, your solution is okay but there is no reason to create a new class simply to share data. You can use a hashtable/array/dictionary or whatever class suits you best to share data. If you want to do something special with the XYZ class, or it has methods you wish to call from it, then you would have to create a new class XYZ and return it. Though, if you just want to share data, use a data structure that's already available to your use.


That would work yes. If it is the most ideal or not is hard to say. Since you are using the variables "ID" and "Name" it kinda indicates that you are working with domain objects from a database, and if so, you will probably need the class for a lot more than just this one method.

What about the class ABC? What kind of class is that? Because you could also do this:

public class abc{
 private int _id;
 private string _name;

 public void DoAction(){
  _id = 5;
  _name = "Dave";
 }

 public void DoStart(){
  var b = _id;
  var c = _name;
 }
}

But remember to use proper naming for your classes, so you have an idea of what they are used for.


Yes, though if your class has trivial properties you can consider using existing .Net classes:

1) You can consider using System.Tuple (.Net 4.0) but you will not have good property names anymore:

var result = Tuple.Create(5, "Dave");
int id = result.Item1;
string name = result.Item2;

2) You can use KeyValuePair if it is applicable:

var result = new KeyValuePair<int, string>(5, "Dave");
int id = result.Key;
string name= result.Value;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜