C# 中的结构体(struct)是一种用户自定义的数据类型,它具有值类型的特点。结构体适用于以下场景:
public struct Point { public double X { get; set; } public double Y { get; set; } } public struct Result { public bool IsSuccess { get; set; } public string Message { get; set; } } public Result CreateUser(string username, string password) { // ... } public struct UserInfo { public string Username { get; set; } public int Age { get; set; } } public void PrintUserInfo(UserInfo userInfo) { Console.WriteLine($"Username: {userInfo.Username}, Age: {userInfo.Age}"); } public struct Color { public byte R { get; set; } public byte G { get; set; } public byte B { get; set; } public enum ColorValues { Red, Green, Blue } } 需要注意的是,结构体不适用于作为大型对象或需要引用语义的情况,因为它们是值类型,可能会导致性能问题和不必要的内存分配。在这种情况下,可以考虑使用类(class)来代替结构体。