在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#中傳遞數據的一些常用方法,可以根據具體的需求選擇合適的方式。