根据函数的输入(.NET C#或VB)返回变量

时间:2012-04-12 08:24:06

标签: c# .net vb.net

说我有以下变量:

Public Shared x As String = "100"
Public Shared y As String = "text"
Public Shared z As String = "something"

我有一个功能:

Function giveVar(ByVal varName As String) As String 

    Return varName
End Function

但这自然不能做我想要的。我想要的是我的函数giveVar返回包含giveVar的变量的值。例如,我调用giveVar("x")我希望我的函数返回"100"

当然这可以通过Select Case完成,但这不是我喜欢做的事情。有没有人有任何建议? 甚至可以根据字符串调用值吗?

[编辑:]

Namespace i18n
    public NotInheritable Class Settings
        Public Shared LanguageCode As String
        Public Shared HideAllLocalizedText As Boolean
    End Class

Public NotInheritable Class i18n
        Private Sub New()

        End Sub

        Public Shared Function t(ByVal varName As String) As String
            Select Case Settings.LanguageCode
                Case "en"
                    Return en(varName)
                Case Else
                    Return nl(varName)
            End Select
        End Function

        Private Shared Function en(ByVal varName As String) As String
            Dim ASP_0344 As String = "Cancel"
            Dim ASP_0807 As String = "Click"
            Dim ASP_0808 As String = "here"
            Dim ASP_0812 As String = "Welcome at the login screen..."

            ' These are examples there is a whole bigger list               

            Return CallByName(Me, varName, vbGet)
        End Function

        Private Shared Function nl(ByVal varName As String) As String
            Dim ASP_0344 As String = "Annuleren"
            Dim ASP_0807 As String = "Klik"
            Dim ASP_0808 As String = "hier"
            Dim ASP_0812 As String = "Welkom op het inlogscherm..."

            Return CallByName(Me, varName, vbGet)
        End Function

    End Class
End Namespace

我认为这项工作到目前为止,但我在CallByName(Me, varName, vbGet)的{​​{1}}上收到以下错误:Me

5 个答案:

答案 0 :(得分:3)

您提出的最简单的实施方案可能是Dictionary

实施例

// c#
var values = new Dictionary<string, string>();
values["x"] = "100";
values["y"] = "text";
values["z"] = "something";

public string GiveVar( string name )
{
   return values[name];
}
'vb.net
Dim values As New Dictionary(Of String, String)
values.Add("x", "100")
values.Add("y", "text")
values.Add("z", "something")

Function giveVar(ByVal varName As String) As String 
    Return values(varName)
End Function

此时,您实际上并不需要函数来获取值。你可以在字典上使用索引器。

如果在运行时之前不知道成员的名称,则可以使用reflection。反射带来(有时是实质性的)性能损失并且可能导致脆弱/不直观的代码,但 - 正确使用 - 是一种强大的工具。

Expando objects也可用于创建类似的代码。通常这不是正确的路径,除非您使用expando对象来改进结构较少的数据。

答案 1 :(得分:2)

是的,您可以使用反射来实现:

Imports System.Reflection

Public Class Test

  Public Shared x As String = "100"
  Public Shared y As String = "text"
  Public Shared z As String = "something"

  Function giveVar(ByVal varName As String) As String

    Dim pi As FieldInfo = Me.GetType().GetField(varName)

    Return (pi.GetValue(Me)).ToString()

  End Function

End Class

测试它:

Module Module1

  Sub Main()

    Dim t As New Test

    Console.WriteLine("x: " & t.giveVar("x"))
    Console.WriteLine("y: " & t.giveVar("y"))
    Console.WriteLine("z: " & t.giveVar("z"))

    Console.ReadKey()

  End Sub

End Module

您需要导入System.Reflection命名空间才能工作,还需要在定义了giveVar()函数的类中定义变量,否则您需要将拥有变量的objet传递给参数并替换Me.GetType()调用。

最后,这不适用于局部变量。

答案 2 :(得分:1)

尝试

CallByName (Me, "x", VbGet)

答案 3 :(得分:0)

将字符串放在Hashtable中,您可以通过键轻松检索它们。 您仍然可以使用硬编码密钥查找公共属性。

答案 4 :(得分:0)

通用解决方案

在c#

using System.Reflection;

public class MyClass
{
    public static string x = "1";
    public static int y = 2;

    public static bool TryGetValue<T>(string variableName, out T value)
    {
        try
        {
            var myType = typeof(MyClass);
            var fieldInfo = myType.GetField(variableName);
            value = (T)fieldInfo.GetValue(myType);
            return true;
        }
        catch
        {
            value = default(T);
            return false;
        }
    }
}

你可以像这样使用

string xValue;
if (MyClass.TryGetValue("x", xValue))
{
    // it worked
}
else
{
    // oops, x is not there or it will not cast to string
}

int yValue;
if (MyClass.TryGetValue("y", yValue))
{
    // it worked
}
else
{
    // oops, x is not there or it will not cast to int
}

但请记住,

string valueX = MyClass.x;
int valueY = MyClass.y;

代码更短,您可以在编译时进行类型检查。