首页 > 解决方案 > Assigning input string value as datamember for example (C#)

问题描述

public class Test {
    public bool Case1 { get; set; }
    public bool Case2 { get; set; }
    public bool Case3 { get; set; }
}

Now if I get input as Case1 as string

public static void Main(String[] args) {
    string test = "Case1";
}

In this particular case if I get input as Case1, I need to assign value of Test.Case1 as true.

标签: c#asp.net-core

解决方案


If you want to use reflection, it would look something like this:

static void Main(string[] args)
{
    string test = "Case1";
    var myTest = new Test();
    var prop = myTest.GetType().GetProperty(test);
    prop.SetValue(myTest, true);
}

This is just a minimal example...in production code you'd want to have some error checking, for example to ensure that prop != null etc.


推荐阅读