开发者

How do you dynamially invoke a property, but only if its argument is a certain type?

开发者 https://www.devze.com 2023-01-20 04:20 出处:网络
I am开发者_开发问答 trying to use reflection to get all the (settable) properties in my POCO (which take a string argument, for now, but I plan to expand to other types), and set them to something arb

I am开发者_开发问答 trying to use reflection to get all the (settable) properties in my POCO (which take a string argument, for now, but I plan to expand to other types), and set them to something arbitrary. (I need to make sure the .Equals method is implemented properly.)

I have some code in my unit tests that looks something like this (where t is the object under test, and u is a default version of that object):

foreach(var property in t.GetType().GetProperties())
{
    var setMethod = property.GetSetMethod();
    var type = setMethod.GetParameters()[0].GetType();
    if(typeof(string).IsAssignableFrom(type))
    {
        setMethod.Invoke(t, new object[] {"a"});
        Assert.IsFalse(t.Equals(u));
        Assert.IsFalse(t.GetHashCode() == u.GetHashCode());
    }                    
}

The place where this fails is where I say typeof(string).IsAssignableFrom(type). The code inside the if { ... } block never runs. How would I properly code up this part of the test?


You have confused ParameterInfo.GetType() with ParameterInfo.ParameterType. You should have:

var type = setMethod.GetParameters()[0].ParameterType;

.GetType() returns the Type of the current object, in this case ParameterInfo, which is obviously not what you want.

0

精彩评论

暂无评论...
验证码 换一张
取 消