将数据从一个类访问到另一个C#类可以通过以下几种方式实现:
public class SourceClass
{
private string data;
public string Data
{
get { return data; }
set { data = value; }
}
}
public class TargetClass
{
public void AccessData()
{
SourceClass source = new SourceClass();
source.Data = "Hello World";
Console.WriteLine(source.Data);
}
}
public class SourceClass
{
private string data;
public void SetData(string newData)
{
data = newData;
}
public string GetData()
{
return data;
}
}
public class TargetClass
{
public void AccessData()
{
SourceClass source = new SourceClass();
source.SetData("Hello World");
Console.WriteLine(source.GetData());
}
}
public class SourceClass
{
private string data;
public SourceClass(string initData)
{
data = initData;
}
public string GetData()
{
return data;
}
}
public class TargetClass
{
private string data;
public TargetClass(SourceClass source)
{
data = source.GetData();
}
public void AccessData()
{
Console.WriteLine(data);
}
}
public class Program
{
public static void Main(string[] args)
{
SourceClass source = new SourceClass("Hello World");
TargetClass target = new TargetClass(source);
target.AccessData();
}
}
以上是将数据从一个类访问到另一个C#类的几种常见方式。根据具体的场景和需求,选择合适的方式来实现数据的访问和传递。
领取专属 10元无门槛券
手把手带您无忧上云