繁体   English   中英

如何将串联字符串转换为Class.Property?

[英]How do I cast a concatenated string to a Class.Property?

我有一个带有几个用于存储常量值的静态字符串的静态类。 例如,Foo.Bar可能返回代表数据库列名的字符串,而Foo.Foo可能返回具有纪元值的字符串。

在我的应用程序中,我需要将类名与字符串名连接起来,以获得所需的值。 例如,我知道班级名称是Foo。 我也知道属性名称是Bar。 但是,属性名称会根据另一个值更改。 在foreach中,我将类名与其他属性名连接起来,以获得字符串“ Foo.Bar”。 到目前为止,我们还可以。 当我将连接的字符串传递到采用字符串的方法中时,它不会从类中检索静态字符串。 换句话说,即使连接字符串正确形成为“ Foo.Bar”,我的方法也不会返回Foo.Bar的值。 如果我对Foo.Bar进行硬编码,则会得到所需的字符串,但这确实需要在运行时完成。

关于如何解决此问题有任何想法吗? 我可以把它扔给什么吗?

public static class Foo
{
    public static string Bar = "Sample Text";
}

public class Program
{
    static void Main()
    {

     // string "Foo.Bar" is built here by combining two strings.

     ...
     // more processing
     ...

     // I need the literal value of Foo.Bar here not literally "Foo.Bar"...

     }
}

如果Foo始终是类,那么您只需传递属性名称即可,而不是连接字符串:

public string GetString(string propertyName)
{
    return typeof(Foo).GetProperty(propertyName).GetValue(null, null);
}

如果不是总是Foo ,则还可以将类型传递给GetString()方法。

反射...

考虑:

public class Foo
{
    public string Bar { get; set; }
}

你可以做:

Foo a = new Foo() { Bar = "Hello!" };
MessageBox.Show(typeof(Foo).GetProperty("Bar").GetValue(a,null) as string);

您需要使用反射。 顺便说一句-请注意,反射速度较慢,可能会在运行时导致错误,对重构工具无响应等。因此,您可能需要重新考虑自己的工作方式; 例如, Dictionary<string, string>似乎更易于管理。

为了进行反思,您需要获取(a)类型,因为似乎您正在引用> 1类,然后获取(b)属性。 就像是:

var lookupKey = "Foo.Bar";
var typeName = lookupKey.Substring(0, lookupKey.LastIndexOf("."));
var propName = lookupKey.Substring(lookupKey.LastIndexOf(".") + 1);

var typeInfo = Type.GetType(typeName, true);
var propInfo = typeInfo.GetProperty(propName);

return propInfo.GetGetMethod().Invoke(null, null);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM