views:

210

answers:

3

Here is what I mean:

I need to be able to substitute this ugly looking C# code:

if (attribute.Name == "Name") machinePool.Name = attribute.Value;
else if (attribute.Name == "Capabilities") machinePool.Capabilities = attribute.Value;
else if (attribute.Name == "FillFactor") machinePool.FillFactor = attribute.Value;

into something like this:

machinePool.ConvertStringToObjectField(attribute.Name) = attribute.Value;

There is no ConvertStringToObjectField() method, but I would like to have something like this, if it's possible. I have access to the machinePool object class code, so I can add neccessary code, but I am not sure what code it may be or is it even possible to do in C#.

+7  A: 

Yes, you can do this through reflection:

var fieldInfo = machinePool.GetType().GetField(attribute.Name);
fieldInfo.SetValue(machinePool, attribute.Value);

You could also create an extension method to make things easier:

public static void SetField(this object o, string fieldName, object value)
{
    var fi = o.GetType().GetField(fieldName);
    fi.SetValue(o, value);
}
Lee
Great example, but don't forget to bring up the fact that reflection is about 1000 times slower than calling a method directly and should be used only for very special circumstances like when dynamically loading a DLL. Sometimes, reflection is not necessary and an alternative methodology should be used (and sometimes not). This link discusses the performance costs: http://stackoverflow.com/questions/25458/how-costly-is-reflection-really
Michael La Voie
A: 

Yes, you can. Here's some code I use when I want to get property names as strings (ie, to handle a PropertyChangedEventHandler) but I don't want to use the strings themselves:

    public static string GetPropertyName<T>(Expression<Func<T, object>> propertyExpression)
    {
        Check.RequireNotNull<object>(propertyExpression, "propertyExpression");
        switch (propertyExpression.Body.NodeType)
        {
            case ExpressionType.MemberAccess:
                return (propertyExpression.Body as MemberExpression).Member.Name;
            case ExpressionType.Convert:
                return ((propertyExpression.Body as UnaryExpression).Operand as MemberExpression).Member.Name;
        }
        var msg = string.Format("Expression NodeType: '{0}' does not refer to a property and is therefore not supported", 
            propertyExpression.Body.NodeType);
        Check.Require(false, msg);
        throw new InvalidOperationException(msg);
    }

And here's some test code to help you work through it:

[TestFixture]
public class ExpressionsExTests
{
    class NumbNut
    {
        public const string Name = "blah";
        public static bool Surname { get { return false; } }
        public string Lame;
        public readonly List<object> SerendipityCollection = new List<object>();
        public static int Age { get { return 12; }}
        public static bool IsMammel { get { return _isMammal; } }
        private const bool _isMammal = true;
        internal static string BiteMe() { return "bitten"; }
    }

    [Test]
    public void NodeTypeIs_Convert_aka_UnaryExpression_Ok()
    {
        Assert.That(ExpressionsEx.GetPropertyName<NumbNut>(nn => NumbNut.Age), Is.EqualTo("Age"));
        Assert.That(ExpressionsEx.GetPropertyName<NumbNut>(nn => NumbNut.IsMammel), Is.EqualTo("IsMammel"));
        Assert.That(ExpressionsEx.GetPropertyName<NumbNut>(nn => NumbNut.Surname), Is.EqualTo("Surname"));
    }

    [Test]
    public void NodeTypeIs_MemberAccess_aka_MemberExpression_Ok()
    {
        Assert.That(ExpressionsEx.GetPropertyName<NumbNut>(nn => nn.SerendipityCollection), Is.EqualTo("SerendipityCollection"));
        Assert.That(ExpressionsEx.GetPropertyName<NumbNut>(nn => nn.Lame), Is.EqualTo("Lame"));
    }

    [Test]
    public void NodeTypeIs_Call_Error()
    {
        CommonAssertions.PreconditionCheck(() => ExpressionsEx.GetPropertyName<NumbNut>(nn => NumbNut.BiteMe()),
                                           "does not refer to a property and is therefore not supported");
    }

    [Test]
    public void NodeTypeIs_Constant_Error() {
        CommonAssertions.PreconditionCheck(() => ExpressionsEx.GetPropertyName<NumbNut>(nn => NumbNut.Name),
                                           "does not refer to a property and is therefore not supported");
    }

    [Test]
    public void IfExpressionIsNull_Error()
    {
        CommonAssertions.NotNullRequired(() => ExpressionsEx.GetPropertyName<NumbNut>(null));
    }

    [Test]
    public void WasPropertyChanged_IfPassedNameIsSameAsNameOfPassedExpressionMember_True()
    {
        Assert.That(ExpressionsEx.WasPropertyChanged<NumbNut>("SerendipityCollection", nn => nn.SerendipityCollection), Is.True);
    }

    [Test]
    public void WasPropertyChanged_IfPassedPropertyChangeArgNameIsSameAsNameOfPassedExpressionMember_True()
    {
        var args = new PropertyChangedEventArgs("SerendipityCollection");
        Assert.That(ExpressionsEx.WasPropertyChanged<NumbNut>(args, nn => nn.SerendipityCollection), Is.True);
    }

}

HTH

Berryl

Berryl
A: 

You could do something like:

void SetPropertyToValue(string propertyName, object value)
{
    Type type = this.GetType();
    type.GetProperty(propertyName).SetValue(this, value, null);
}

Then use it like:

machinePool.SetPropertyToValue(attribute.Name, attribute.Value);
Reed Copsey