Установка/получение свойств класса по имени строки
Я пытаюсь установить значение свойства в классе с помощью строки. Например, мой класс имеет следующие свойства:
myClass.Name
myClass.Address
myClass.PhoneNumber
myClass.FaxNumber
Все поля имеют string
тип, поэтому я заранее знаю, что это всегда строка. Теперь я хочу иметь возможность устанавливать свойства, используя строку, как вы могли бы сделать с объектом DataSet
. Что-то вроде этого:
myClass["Name"] = "John"
myClass["Address"] = "1112 River St., Boulder, CO"
В идеале я хочу просто назначить переменную, а затем установить свойство, используя имя этой строки из переменной:
string propName = "Name"
myClass[propName] = "John"
Я читал об отражении и, возможно, это был способ сделать это, но я не уверен, как это настроить, сохраняя доступ к свойству в классе нетронутым. Я хочу все еще иметь возможность использовать:
myClass.Name = "John"
Любые примеры кода были бы действительно хороши.
Ответы
Ответ 1
Вы можете добавить свойство indexer, псевдокод:
public class MyClass
{
public object this[string propertyName]
{
get{
// probably faster without reflection:
// like: return Properties.Settings.Default.PropertyValues[propertyName]
// instead of the following
Type myType = typeof(MyClass);
PropertyInfo myPropInfo = myType.GetProperty(propertyName);
return myPropInfo.GetValue(this, null);
}
set{
Type myType = typeof(MyClass);
PropertyInfo myPropInfo = myType.GetProperty(propertyName);
myPropInfo.SetValue(this, value, null);
}
}
}
Ответ 2
Добавить в любой Class
:
public class Foo
{
public object this[string propertyName]
{
get { return this.GetType().GetProperty(propertyName).GetValue(this, null); }
set { this.GetType().GetProperty(propertyName).SetValue(this, value, null); }
}
public string Bar { get; set; }
}
Затем вы можете использовать как:
Foo f = new Foo();
// Set
f["Bar"] = "asdf";
// Get
string s = (string)f["Bar"];
Источник: Получить значение свойства из строки, используя отражение в С#
Ответ 3
Вы можете добавить индексатора в свой класс и использовать отражение для свойств:
using System.Reflection;
public class MyClass {
public object this[string name]
{
get
{
var properties = typeof(MyClass)
.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in properties)
{
if (property.Name == name && property.CanRead)
return property.GetValue(this, null);
}
throw new ArgumentException("Can't find property");
}
set {
return;
}
}
}
Ответ 4
Может быть что-то вроде этого?
public class PropertyExample
{
private readonly Dictionary<string, string> _properties;
public string FirstName
{
get { return _properties["FirstName"]; }
set { _properties["FirstName"] = value; }
}
public string LastName
{
get { return _properties["LastName"]; }
set { _properties["LastName"] = value; }
}
public string this[string propertyName]
{
get { return _properties[propertyName]; }
set { _properties[propertyName] = value; }
}
public PropertyExample()
{
_properties = new Dictionary<string, string>();
}
}