C# 将结构传递给另一个类
我在一个C类中有一个结构数组,我想将该数据传递到另一个类中 这是我的密码C# 将结构传递给另一个类,c#,C#,我在一个C类中有一个结构数组,我想将该数据传递到另一个类中 这是我的密码 private struct strClassOfService { public string COS; public string myValue; } private strClassOfService[] arrCOS = null; // // some code that loads arrCOS with data // // // here is where i will instan
private struct strClassOfService
{
public string COS;
public string myValue;
}
private strClassOfService[] arrCOS = null;
//
// some code that loads arrCOS with data
//
//
// here is where i will instantiate another class and
// set the arrCOS so I can use it in the other class
//
如果所有这些都失败了,我想我可以在另一个类中重新加载数据。但我很好奇是否有办法。到目前为止,我的尝试都失败了 首先,如果您打算将结构传递给另一个类,那么应该将结构定义公开,或者至少是内部的。。。一旦这样做,就可以使用各种方法属性、方法调用等将数据复制到其他类 下面显示了两种技术,当然,您只需要使用一种
public class Foo1
{
public struct Bar
{
string A;
string B;
}
private Bar[] data;
// Using a method
public Bar[] ExportData()
{
return data;
}
// Using properties
public Bar[] DataProperty
{
get { return data; }
}
}
public class Foo2
{
private Foo1.Bar[] data;
// Using a method
public void ImportData(Foo1 source)
{
this.data = source.ExportData();
}
// Using properties
public Foo1.Bar[] DataProperty
{
get { return data; }
}
public void ReadProperty(Foo1 source)
{
this.DataProperty = source.DataProperty;
}
}
如果你不想让你的结构公开,你可以考虑声明它是内部的:这样,它只能访问同一个程序集中的其他类。
你能详细说明你的尝试是如何失败的还是为什么失败的。演示如何尝试传递数组并在其他类中使用它。从您的帖子中,我无法判断您是否看到编译时或运行时逻辑错误。我收到了一个编译器错误。我不记得确切的错误,但在做了一些研究之后,我能够将它传递到类B的方法中,并以这种方式加载它。我不知道这是否是最有效的方法,但我的最后期限是下周。希望我有时间自己去探索它。我会尝试设置内部结构。谢谢