C# 对象扩展静态方法实现属性设置 - 简洁高效
在 C# 中,可以使用扩展方法为现有的对象添加新的方法。扩展方法可以用于设置对象的属性或字段的值。下面是一个示例:
public static class ObjectExtensions
{
public static void SetProperty<T>(this T obj, string propertyName, object value)
{
var propertyInfo = obj.GetType().GetProperty(propertyName);
if (propertyInfo != null)
{
propertyInfo.SetValue(obj, value);
}
}
}
在上面的示例中,我们定义了一个名为 'SetProperty' 的扩展方法,它接受一个对象、一个属性名称和一个值作为参数。该方法首先获取对象的类型,并使用属性名称获取相应的 'PropertyInfo' 对象。然后,通过 'SetValue' 方法将值设置到该属性上。
使用该扩展方法的示例如下:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
var person = new Person();
person.SetProperty('Name', 'John');
person.SetProperty('Age', 30);
Console.WriteLine($'Name: {person.Name}, Age: {person.Age}');
}
}
在上面的示例中,我们创建了一个 'Person' 类,它有两个属性 'Name' 和 'Age'。然后,我们通过调用 'SetProperty' 扩展方法来设置对象的属性值。最后,我们打印出属性的值。
输出结果为:
Name: John, Age: 30
使用对象扩展静态方法可以方便地为现有的对象添加新的功能,如设置属性的值。但需要注意的是,扩展方法只能在静态类中定义,并且必须通过命名空间的导入才能使用。
原文地址: https://www.cveoy.top/t/topic/myLO 著作权归作者所有。请勿转载和采集!