开发者

Checking a field of a generic type

public static int GetResult<TType>(TType aObject) {
    if(aObject.mValue==12)
        return 99;
    return 20;
}

How can I check the field mValue of TType, I'm guessing reflection may co开发者_如何学JAVAme into this, but I'm unsure how?

Thanks.


Generics are useful when you want to preserve strong typing and compile-time safety. If you are going to resort to Reflection no need to use generics. So one way would be to define an interface or a base class containing this property:

public interface IFoo
{
    int Value { get; set; }
}

and then have a generic constraint on the type:

public static int GetResult<TType>(TType aObject) where TType: IFoo
{
    if(aObject.Value == 12)
    {
        return 99;
    }
    return 20;
}


Here's a pattern that I use:

First create an interface:

IFoo
{
    int mValue {get; }
}

Then an "adhoc" class that implements the interface

AdHocIFoo : IFoo
{
    Func<int> get_mValue;

    public AdHocIFoo(Func<int> getValue)
    {
         this.get_mValue = getValue;
    }

    public int mValue { get { return get_mValue(); } }

}

Now, if you have types, say, Bar and Person defined like this:

class Bar
{
    public int Baz { get; set; }
}

class Person
{
    public int ID {get; set; }
}

Then you can use code similar to the following;

var bar = new Bar() { Baz = 3 };
var per = new Person() { ID = 43 };

var foo1 = new AdHocIFoo(x => bar.Baz);
var foo2 = new AdHocIFoo(x => per.ID);

var result1 = GetResult<AdHocIFoo>(foo1);
var result2 = GetResult<AdHocIFoo>(foo2);


You'd need to restrict TType using the 'where' keyword to a type or interface which you know has a mValue field.

If you don't want to do that, you can use the dynamic keyword e.g.

dynamic value= aObject
if (value.mValue == 12)
    return 99;
return 20;

But this should be a last resort as it will fail at runtime if your object doesn't have a mValue.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜