gpt4 book ai didi

C# 匿名类和列表
转载 作者:行者123 更新时间:2023-12-03 19:15:48 25 4
gpt4 key购买 nike

我想访问列表中函数返回的结构。我无法这样做,因为它会导致编译器错误。

public class StructTypeA
{
public string sString1;
public string sString2;
}
public class StructTypeB
{
public int iNum1;
public int iNum2;
}

public List<object> myFunction ()
{

StructTypeA myStructA = new StructTypeA();
StructTypeB myStructB = new StructTypeB();

var response = new List<object> { new {oStructA = myStructA} , new {oStructB = myStructB } };

return response;
}

public void myCallerFunction()
{
var retVal = myFunction ();

//This does not work, it generates a compile error
// 'object' does not contain a definition for 'oStructA' and no extension method 'oStructA' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
var myStr = retVal[0].oStructA.sString1;


//How can I access the structures.
}

我想访问结构 oStructA 和 oStructB,请告诉我确切的语法应该是什么。

最佳答案

您返回的是 List<object> , 所以 retVal[0]将是 object 类型, 它没有 oStructA成员(member)。

您正在创建一个 List包含匿名类型的实例。您将无法在创建类型的范围之外按名称访问这些成员。

您要么必须为列表创建命名类型:

class MyType
{
public StructTypeA oStructA { get; set; }
public StructTypeB oStructB { get; set; }
}

然后编写您的方法以返回 List<MyType> .

创建此类型的实例就像创建匿名类型的实例一样。使用您的代码示例,只需在 new 之后添加类型名称:

var response = new List<object> { new MyType {oStructA = myStructA} , new Mytype {oStructB = myStructB } };

或者您可以使用 Tuple ,并返回一个列表。

或者,正如其他人所说,使用 dynamic .不过,我一般不建议这样做。命名类型可能是最好的方式。

关于C# 匿名类和列表<object>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14735836/

25 4 0