Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

c# - How to to return a DataTable and an Integer from a method?

What's the easiest way to return two variables from a method? I want to return a DataTable and an Integer.

Private SomeType someMethod()
{
   int x=0;
   Datatable y;
   //return x and y
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ultimately, "best" is subjective and depends on your scenario. We can present options, but "best" is local to you.

There are various ways of returning multiple values; out is very efficient, but not very flexible, and many people find it confusing (indeed, some would say it is an anti-pattern). But for example:

DataTable Foo(out int val) {
   ...
   val = something
   return dataTable;
}

Perhaps more convenient is to declare a return type that encapsulates the two values:

FooResult Foo() {
   ...
   return new FooResult { Table = dataTable, Value = val };
}

where FooResult is a class with 2 properties. This has the advantage that you can add more properties trivially, without changing the API.

Similarly, you could return a Tuple<DataTable,int> - but I advise against it as it expresses nothing about what each value represents. In a Tuple<string,int,string>, what is Item1 ? how is it different to Item3 ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...