C# 函数返回特定字符串的内容

C# 函数返回特定字符串的内容,c#,string,C#,String,函数可以读取/返回名称传递给它的字符串的值吗 例如,如果字符串的值不是“0”,我希望通过告诉函数我希望它检查哪个字符串来返回true public static bool IsEnabled(string sName) { if (TenderTypes.<sName> != "0") { return true; } else { return false; } } 公共静态bool已启用(字符串s

函数可以读取/返回名称传递给它的字符串的值吗

例如,如果字符串的值不是“0”,我希望通过告诉函数我希望它检查哪个字符串来返回true

public static bool IsEnabled(string sName)
{
    if (TenderTypes.<sName> != "0")
    {
        return true;
    }
    else 
    {
        return false;
    }
}
公共静态bool已启用(字符串sName)
{
如果(投标类型)!=“0”)
{
返回true;
}
其他的
{
返回false;
}
}

这主要是为了在编码时加快速度,我希望能够将字符串保留在那里,但同时我希望能够通过将其值从字符串数字更改为零来禁用它们。

不知道您想要实现什么,您的语法看起来像是在试图查询一些通用的
。。。这是不可能的

也许一个简单的方法可以帮助你


如果您的“设置”已启用或禁用,则创建一个
新词典也会对您有所帮助。

假设您有这样的功能:

class TenderTypes
{
    static string myStr = "Some value";
    static string anotherStr = "A different value";
    // ...
};
public static bool IsEnabled(string sName)
{
    if (TenderTypes.strings[sName] != "0")
    {
        return true;
    }
    else 
    {
        return false;
    }
}
public static bool IsEnabled(string sName)
{
    var type = typeof(TenderTypes);
    var field = type.GetField(sName, BindingFlags.Static);
    if (field.GetValue(null) != "0")
    {
        return true;
    }
    else 
    {
        return false;
    }
}
您希望通过字段名查询该字符串(例如
“myStr”

嗯,这可以通过反思来实现。但首先是另一种选择:


使用字典
使用反射 然后你可以这样写你的方法:

class TenderTypes
{
    static string myStr = "Some value";
    static string anotherStr = "A different value";
    // ...
};
public static bool IsEnabled(string sName)
{
    if (TenderTypes.strings[sName] != "0")
    {
        return true;
    }
    else 
    {
        return false;
    }
}
public static bool IsEnabled(string sName)
{
    var type = typeof(TenderTypes);
    var field = type.GetField(sName, BindingFlags.Static);
    if (field.GetValue(null) != "0")
    {
        return true;
    }
    else 
    {
        return false;
    }
}

我需要使用反射方法,因为我已经对此时无法更改的其他位使用了
TenderTypes.name