开发者

Generic Lookup Method

I'm wanting to create a generic lookup method to where you specify a type of object and some other identifying parameters and the method returns an object of that type. Is this 开发者_Python百科possible?

I'm thinking something like this.

public T GetObjectOfType(Guid ID, typeof(T Class))
{
     //lookup this object and return it as type safe
}

I know this just won't work but i hope it explains the concept


You can use a generic method for this:

public T GetObjectOfType<T>(Guid id) where T: class, new()
{
    if (id == FooGuid) //some known identifier
    {
        T t= new T(); //create new or look up existing object here
        //set some other properties based on id?
        return t;
    }
    return null;
}

If all you want is create an instance of a specific type you do not need the additional id parameter, I assume you want to set some properties etc. based on the id. Also your class must provide a default constructor, hence the new() constraint.


Typically factory methods do not take the type of object to create. They return a type that implements some common interface and the concrete, underlying type is dependent on some argument, typically an enumerated value. A simple example:

interface Whatever
{
    void SomeMethod();
}

class A : Whatever { public void Whatever() { } }

class B : Whatever { public void Whatever() { } }

enum WhateverType { TypeA, TypeB }

public void GetWhatever( WhateverType type )
{
    switch( type )
    {
        case WhateverType.TypeA:
            return new A();
            break;
        case WhateverType.TypeB:
            return new B();
            break;
        default:
            Debug.Assert( false );
    }
}

There you have type safety. I'm not sure how you would implement something like that with generics as you need to supply the generic argument at compile time.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜