在C#中,可以通过以下几种方式来传递数据:
void PrintMessage(string message)
{
Console.WriteLine(message);
}
string myMessage = "Hello, World!";
PrintMessage(myMessage);
int Add(int x, int y)
{
return x + y;
}
int result = Add(3, 5);
Console.WriteLine(result); // Output: 8
class Person
{
public string Name { get; set; }
}
Person person = new Person();
person.Name = "Alice";
Console.WriteLine(person.Name); // Output: Alice
class Publisher
{
public event EventHandler<string> DataReceived;
public void SendData(string data)
{
DataReceived?.Invoke(this, data);
}
}
class Subscriber
{
public Subscriber(Publisher publisher)
{
publisher.DataReceived += HandleDataReceived;
}
private void HandleDataReceived(object sender, string data)
{
Console.WriteLine(data);
}
}
Publisher publisher = new Publisher();
Subscriber subscriber = new Subscriber(publisher);
publisher.SendData("Hello, World!"); // Output: Hello, World!
这些是在C#中传递数据的一些常用方法,可以根据具体的需求选择合适的方式。