c#消除开关要求 [英] c# eliminate switch requirement

查看:43
本文介绍了c#消除开关要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的案例值文本总是等于代码中的相关 OSResultStruct,用于我现在实现它并正在工作的方式".例如,如果案例是 osedition,则属性是 OSResultStruct.OSEdition.

My case value text is always be equals to the relevant OSResultStruct in the code for "The way i have it implemented now and is working".So for example if the case is osedition then the property is OSResultStruct.OSEdition.

是否可以执行以下代码行之类的操作?如果是这样,那么我可以用一行代码替换我的 switch 语句.

Is it possible to do something like the line of code below? If so then i can replace my switch statement with one line of code.

lstNewItems[i].sItemValue = OSresult.OSResultStruct."lstNewItems[i].sItemName.ToString().ToUpper()";

我现在使用它并且正在工作的方式

 switch (lstNewItems[i].sItemName)
        {
          case "osedition":
          lstNewItems[i].sItemValue = OSresult.OSResultStruct.OSEdition;
          break;
          case "osbuild":
          lstNewItems[i].sItemValue = OSresult.OSResultStruct.OSBuild;
          break;
          case "osmajor":    
          //.....

推荐答案

Try Reflection:-

Try Reflection:-

OSresult.OSResultStruct.GetType().GetProperty(lstNewItems[i].sItemName,BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance).GetValue(OSresult.OSResultStruct, null)

对于更通用的方法:-

定义一个扩展类:-

public static class ClassExtensions
    {
        public static TRes GetPublicPropertyValue<T,TRes>(this T queryObject, string propertyMatch) 
            where T : class,new()
            where TRes : new()

        {
            return (TRes)typeof(T).GetProperty(propertyMatch, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance).GetValue(queryObject, null);
        }
    }

将其用于任何可实例化类型,如下所示:-

Use it for any instantiable type as follows:-

OSresult.OSResultStruct.GetPublicPropertyValue<yourtype,yourreturntype>(attribName);

这篇关于c#消除开关要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆