c# 给类增加属性
时间: 2023-07-27 10:24:26 浏览: 64
在 C# 中,可以使用类的扩展方法来给类增加属性。下面是一个示例代码:
```csharp
public static class MyClassExtensions
{
public static int MyProperty(this MyClass obj)
{
return obj.SomeValue * 2;
}
}
public class MyClass
{
public int SomeValue { get; set; }
}
public class Program
{
public static void Main()
{
MyClass obj = new MyClass();
obj.SomeValue = 123;
Console.WriteLine(obj.MyProperty()); // 输出 246
}
}
```
该示例代码使用了一个名为 `MyProperty` 的扩展方法来给 `MyClass` 类增加了一个属性。该属性返回了 `SomeValue` 值的两倍。在主函数中,创建了一个 `MyClass` 对象,并设置了 `SomeValue` 的值,然后输出了 `MyProperty` 的值。
相关问题
c# 给类增加不同名称属性
在 C# 中,可以使用类的扩展方法来给类增加不同名称的属性。下面是一个示例代码:
```csharp
public static class MyClassExtensions
{
public static int GetMyProperty(this MyClass obj)
{
return obj.SomeValue * 2;
}
public static void SetMyProperty(this MyClass obj, int value)
{
obj.SomeValue = value / 2;
}
}
public class MyClass
{
public int SomeValue { get; set; }
}
public class Program
{
public static void Main()
{
MyClass obj = new MyClass();
obj.SetMyProperty(123);
Console.WriteLine(obj.GetMyProperty()); // 输出 123
}
}
```
该示例代码使用了名为 `GetMyProperty` 和 `SetMyProperty` 的扩展方法来给 `MyClass` 类增加了两个不同名称的属性。`GetMyProperty` 方法返回了 `SomeValue` 值的两倍,而 `SetMyProperty` 方法将传入的值除以 2 并赋值给 `SomeValue`。在主函数中,创建了一个 `MyClass` 对象,并使用 `SetMyProperty` 方法设置了 `SomeValue` 的值,然后输出了 `GetMyProperty` 的值,结果为 123。
c# 给类增加多个属性
在 C# 中,可以使用类的扩展方法来给类增加多个属性。下面是一个示例代码:
```csharp
public static class MyClassExtensions
{
public static int GetMyProperty1(this MyClass obj)
{
return obj.SomeValue * 2;
}
public static void SetMyProperty1(this MyClass obj, int value)
{
obj.SomeValue = value / 2;
}
public static string GetMyProperty2(this MyClass obj)
{
return obj.SomeValue.ToString();
}
public static void SetMyProperty2(this MyClass obj, string value)
{
obj.SomeValue = int.Parse(value);
}
}
public class MyClass
{
public int SomeValue { get; set; }
}
public class Program
{
public static void Main()
{
MyClass obj = new MyClass();
obj.SetMyProperty1(123);
Console.WriteLine(obj.GetMyProperty1()); // 输出 123
obj.SetMyProperty2("456");
Console.WriteLine(obj.GetMyProperty2()); // 输出 456
}
}
```
该示例代码使用了名为 `GetMyProperty1`、`SetMyProperty1`、`GetMyProperty2` 和 `SetMyProperty2` 的扩展方法来给 `MyClass` 类增加了两个不同名称的属性。`GetMyProperty1` 方法返回了 `SomeValue` 值的两倍,而 `SetMyProperty1` 方法将传入的值除以 2 并赋值给 `SomeValue`。`GetMyProperty2` 方法返回了 `SomeValue` 的字符串表示,而 `SetMyProperty2` 方法将传入的字符串解析为整数并赋值给 `SomeValue`。在主函数中,创建了一个 `MyClass` 对象,并使用 `SetMyProperty1` 和 `SetMyProperty2` 方法设置了 `SomeValue` 的值,然后输出了 `GetMyProperty1` 和 `GetMyProperty2` 的值,结果分别为 123 和 456。