我可以使用 Reflection 设置属性值吗?

发布于 2024-12-08 21:03:39 字数 168 浏览 1 评论 0原文

我知道我的 C# 类中的属性名称。是否可以使用反射来设置该属性的值?

例如,假设我知道属性的名称是 string propertyName = "first_name";。实际上存在一个名为 first_name 的属性。我可以使用这个字符串来设置它吗?

I know the name of a property in my C# class. Is it possible to use reflection to set the value of this property?

For example, say I know the name of a property is string propertyName = "first_name";. And there actaully exists a property called first_name. Can I set it using this string?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

水水月牙 2024-12-15 21:03:39

是的,您可以使用反射 - 只需使用 Type.GetProperty(如有必要,指定绑定标志),然后调用 SetValue 适当地。示例:

using System;

class Person
{
    public string Name { get; set; }
}

class Test
{
    static void Main(string[] arg)
    {
        Person p = new Person();
        var property = typeof(Person).GetProperty("Name");
        property.SetValue(p, "Jon", null);
        Console.WriteLine(p.Name); // Jon
    }
}

如果它不是公共属性,则需要指定 BindingFlags.NonPublic | GetProperty 调用中的 BindingFlags.Instance。

Yes, you can use reflection - just fetch it with Type.GetProperty (specifying binding flags if necessary), then call SetValue appropriately. Sample:

using System;

class Person
{
    public string Name { get; set; }
}

class Test
{
    static void Main(string[] arg)
    {
        Person p = new Person();
        var property = typeof(Person).GetProperty("Name");
        property.SetValue(p, "Jon", null);
        Console.WriteLine(p.Name); // Jon
    }
}

If it's not a public property, you'll need to specify BindingFlags.NonPublic | BindingFlags.Instance in the GetProperty call.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文