I have a method in C# that has to return 2 different objects based on input parameter.
How can that be done?
var nextPage = new LoadByContentType(1);
await App.Navigator.PushAsync(nextPage);
private ???? LoadByContentType(int Param1)
{
if (Param1 == 1)
return new ListPage(Param1);
else
return new WebviewPage(Param1);
}
Use the common base type of both types (as @Sriram Sakthivel suggested) or use the base class for all other classes object
:
Supports all classes in the .NET Framework class hierarchy and provides low-level services to derived classes. This is the ultimate base class of all classes in the .NET Framework; it is the root of the type hierarchy.
https://msdn.microsoft.com/en-us/library/system.object%28v=vs.110%29.aspx
@ITGuy mentioned that ContentPage
is the base class shared by both ListPage
and WebviewPage
so one working version of your code would be:
private ContentPage LoadByContentType(int Param1)
{
if (Param1 == 1)
return new ListPage(Param1);
else
return new WebviewPage(Param1);
}
You could create create a common class for the two object to inherit from with an enum for example to safely get the desired object.
public enum PageTypeEnum{ ListPage,WebviewPage};
public abstract class BasePage
{
//Common data..
public abstract PagetTypeEnum PageType{get;}
}
public class ListPage : BasePage
{
public overide PageTypeENum PageType {get{return PageTypeEnum.ListPage;}}
}
public class WebviewPage: BasePage
{
public overide PageTypeENum PageType {get{return PageTypeEnum.WebviewPage;}}
}
Usage:
private static BasePage LoadByContentType(int Param1)
{
if (Param1 == 1)
return new ListPage(Param1);
else
return new WebviewPage(Param1);
}
Use output parameters
private static BasePage LoadByContentType(int Param1, out int Param2, out int Param3)
{
Param1 = 1;
Param2 = 2;
return something;
}
To call it you can do:
int int1, int2;
var something = LoadByContentType(1, out int1, out int2);
More information on C# out parameters are at: https://msdn.microsoft.com/en-us/library/t3c3bfhx.aspx
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.