![](/img/trans.png)
[英]c#, How to use a string not as a string but as the name of an object in another class?
[英]C# use string as a class field name
對不起,如果瓷磚有誤導性。 我想要做的是使用一個字符串來獲取類中的值。 我有的:
class foo
{
public string field1 {get;set;}
public string field2 {get;set;}
}
public void run()
{
//Get all fields in class
List<string> AllRecordFields = new List<string>();
Type t = typeof(foo);
foreach (MemberInfo m in t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
AllRecordFields.Add(m.Name);
}
foo f = new foo();
foreach(var field in AllRecordFields)
{
//field is a string with the name of the real field in class
f.field = "foobar";
}
}
這是一個非常簡單的例子,所以問題在於f.field = "foobar";
該field
是一個字符串,其中包含我想要賦值的真實類字段的名稱。
使用PropertyInfo
代替MemberInfo
,然后使用SetValue
。
public void run()
{
foo f = new foo();
Type t = typeof(foo);
foreach (PropertyInfo info in t.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
info.SetValue(f, "foobar", new object[0]);
}
}
首先,最好使用屬性而不是字段。 其次,您的字段是私有的,不能從foo外部訪問。 您需要將它們聲明為公開。
對於您的示例,您必須使用反射來訪問這些文件。 但這很慢,風格也不是很好。 您最好直接使用該類(使用屬性設置器)或使用接口。
將方法添加到foo類中以更改所有屬性
class foo
{
public string field1 {get;set;}
public string field2 { get; set; }
public void SetValueForAllString( string value)
{
var vProperties = this.GetType().GetProperties();
foreach (var vPropertie in vProperties)
{
if (vPropertie.CanWrite
&& vPropertie.PropertyType.IsPublic
&& vPropertie.PropertyType == typeof(String))
{
vPropertie.SetValue(this, value, null);
}
}
}
}
foo f = new foo() { field1 = "field1", field2 = "field2" };
f.SetValueForAllString("foobar");
var field1Value = f.field1; //"foobar"
var field2Value = f.field2; //"foobar"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.