What is the best way of passing both a List<T>
and a bool
as the returning value of a method? Right now I have this custom class called BoolList
acting like a container but I was wondering if there is a better and/or more elegant way of doing it.
问问题
124 次
3 回答
4
为什么不使用元组?
http://www.dotnetperls.com/tuple
http://msdn.microsoft.com/en-us/library/dd268536.aspx
然后你有一个类型安全的容器,而不必创建一个类。
private Tuple<List<int>, bool> myMethod()
{
var myList = new List<int>();
var myBool = true;
return new Tuple<List<int>, bool>(myList, myBool);
}
于 2013-09-11T09:52:16.927 回答
3
您可以使用Tuple<List<T>, bool>
public Tuple<List<string>, bool> MethodName()
{
return Tuple.Create(new List<string>(), true);
}
或使List<T>
out
参数和bool
正常返回(就像TryParse
方法一样)
public bool MethodName(out List<string> results)
{
results = new List<string>();
return true;
}
于 2013-09-11T09:52:52.487 回答
1
正如这里已经提到的,您可以使用元组,这是一个很好的解决方案。唯一的缺点是您使用非信息性名称 Item1、Item2 引用元组中的项目...如果您要经常返回相同的类型,或者您将在描述性属性提高可读性的地方传递结果,那么另一种(老式)方法是拥有一个类(或本答案中进一步描述的结构),其返回类型作为属性并返回该类的实例。例如,类定义可能是当前类的本地定义。
public class EmployeeSearchResult
{
public List<Employee> Employees{get;set;}
public bool Success{get;set;}
}
private EmployeeSearchResult Search()
{
var employeeSearchResult = new EmployeeSearchResult();
employeeSearchResult.Employees = new List<Employee>();
employeeSearchResult.SearchSuccess = true;
return employeeSearchResult;
}
由于返回通常是小而轻量级的,而且生命周期很短,因此结构可能是比类更好的选择。但是,请注意何时适合使用结构 - 根据msdn: -
√ 如果类型的实例很小且通常短暂存在或通常嵌入在其他对象中,请考虑定义结构而不是类。
X 避免定义结构,除非该类型具有以下所有特征:
- 它在逻辑上表示单个值,类似于原始类型(int、double 等)。
- 它的实例大小小于 16 个字节。
- 它是不可变的。
- 它不必经常装箱。
于 2013-09-11T10:12:07.967 回答