c# - 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.
解决方案
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.
推荐阅读
- html - 如何在 CSS 中使用鼠标滚轮水平滚动 div?
- google-chrome - chrome headless print-to-pdf has poor quality
- spring - PayloadRootSmartSoapEndpointInterceptor Intercepts multiple EndPoints
- c# - 如何使用 MediatR 正确实现 Result 对象程序流程?
- unity3d - “signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x200000077” 在华为设备上崩溃
- symfony - 从我的 QuizRepository 获取我的 querybuilder 结果到我的 QuizController
- microsoft-graph-api - 如何检索对 Microsoft Teams 电话系统呼叫队列进行的呼叫的 callRecords 或日志?
- java - 带有 Socks4 代理的 Java Socket 更改为 Socks5
- javascript - 将具有键值对的对象数组转换为单个对象?
- python - 检查是否存在多个关键字并使用 python 创建另一列