我有以下方法:
public static ?? GetType6()
{
var name = "x";
var age = 1;
return ??
}
像这样调用:
var ?? = GetType6();
我希望能够调用该方法并取回姓名和年龄。我想创建一个匿名对象,但如果我这样做,我该如何解码它?
我有以下方法:
public static ?? GetType6()
{
var name = "x";
var age = 1;
return ??
}
像这样调用:
var ?? = GetType6();
我希望能够调用该方法并取回姓名和年龄。我想创建一个匿名对象,但如果我这样做,我该如何解码它?
你为什么不创建一个类型来保存你想要的任何东西?
public static MyType GetType6()
{
MyType type = new MyType();
type.name = "x";
type.age = 1;
return type;
}
class MyType
{
public string name {get;set;}
public int age {get;set;}
public MyType()
{
}
}
最简单的方法是返回一个Tuple<string, int>
(从 .NET 4 开始可用):
public static Tuple<string, int> GetType6()
{
var name = "x";
var age = 1;
return Tuple.Create(name, age);
}
您可以通过这种方式读取值:
var pair = GetType6();
string name = pair.Item1;
int age = pair.Item2;
当然更健壮、可读和可维护的是创建一个类:
class User
{
public string Name { get; set; }
public int Age{ get; set; }
}
public static User GetUser()
{
var name = "x";
var age = 1;
return new User{Name = name, Age = age };
}
var user = GetUser();
string name = user.Name;
int age = user.Age;
您可以使用元组:
public Tuple<int, int> GetMultipleValue()
{
return new Tuple<int,int>(1,2);
}
您可以在此处了解更多详细信息:http: //msdn.microsoft.com/en-us/library/system.tuple.aspx
使用out
关键字,可能如下:
public static string GetType6(out int age)
{
var name = "x";
var age = 1;
return name
}
out
关键字导致参数通过引用传递。ref
需要在传递之前初始化变量。注意:使用它是不好的做法。
用作dynamic
返回类型:
public static dynamic GetType6()
{
var name = "x";
var age = 1;
return new { name = "x", age = 1 };
}
方法调用:
var v = GetType6();
所以问题: C#
MSDN中方法的变量返回类型:http: //msdn.microsoft.com/en-us/library/vstudio/dd264741.aspx
You could use anonymous types as you said. Like this.
public static object GetType6()
{
return new { name = "x", age = 1 };
}
To read the values you have to use reflection.
var foo = GetType6();
var name = foo.GetType().GetProperty("name").GetValue(foo, null);
var age = foo.GetType().GetProperty("age").GetValue(foo, null);
Though it's a very dirty way of accomplishing what you need.