[英]C#: Pass Data from Controller to Application Layer to DBContext Layer
[英]In c#, Is it possible to pass two different classes as return type from one layer to other layer?
我的应用程序具有n层体系结构。 我有不同的层(业务逻辑和数据链接和GUI)。 我正在使用一些通用类将数据从一层传递到另一层。 我有一个类(比如RetrnValueCls
),它只有两个变量Return value
和Return Message
。 当我将数据从一层传递到另一层时,我需要返回此Return Value
类以及具有其他变量的另一类(例如MasterItemsCls
)。
以下是方法
public MasterItemsCls GetMasterItemsMDL()
{
/* Does some computations and assign them to
attributes of MasterItemsCls and pass it other methods in other layers. */
}
public ReturnValueCls GetMasterItemsMDL()
{
/* Does some computations and assign them to
attributes of ReturnValueCls and pass it other methods in other layers. */
}
我想立即返回上述两个类( MasterItemsCls
和ReturnValueCls
)作为方法GetMasterItemsMDL
返回类型,而且我也不想合并这两个类。 请让我知道我是否有办法。
一个函数只能返回一个值,因此从这个意义上讲,答案是否定的。
函数可以具有out
参数,因此您可以通过out
参数返回两个值之一。
在我看来,处理此问题的最干净方法是使用第三类来包含其他两个类。 Tuple<T1,T2>
可以用于此目的:
public Tuple<MasterItemsCls, ReturnValueCls> MyFunction()
{
// Do stuff
return new
Tuple<MasterItemsCls, ReturnValueCls>(myMasterItemsCls, myReturnValueCls);
}
Tuple<T1,T2>
一个缺点是,将值作为不太直观的Item1
和Item2
进行访问。
如果您不想使用Tuple<T1,T2>
,则可以轻松创建自己的类以包含MasterItemsCls
和ReturnValueCls
。 那是我的首选方法。
您不需要合并两个类,但是可能的直接方法是生成一个包含要返回的每个类的一个实例的类。
public class YouClassName
{
public MasterItemsCls MasterItemsCls {get; set;}
public ReturnValueCls ReturnValueCls {get; set;}
}
一个方法只能返回一个对象。 您可能会创建其他一些类,这些类具有其他每个类的实例。
泛型作为您的return元素的包装可能会有所帮助。
您可以执行以下操作:
public ReturnValueCls<MasterItemsCls> GetMasterItemsMDL()
{
}
您的ReturnValueCls<T>
需要一个类型参数作为其返回类型。 因此,您的retun类型可以充当所需退货的包装,并能够保留您的退货消息。
类定义的示例。 可能需要一些约束:
public class ReturnValueCls<T>
{
public T Value { et; set;}
public string Message {get; set;}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.