简体   繁体   English

通用查找方法

[英]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.我想创建一个通用查找方法,您可以在其中指定 object 类型和一些其他标识参数,并且该方法返回该类型的 object。 Is this 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.如果您只想创建一个特定类型的实例,则不需要额外的 id 参数,我假设您想根据 id 设置一些属性等。 Also your class must provide a default constructor, hence the new() constraint.此外,您的 class 必须提供默认构造函数,因此new()约束。

Typically factory methods do not take the type of object to create.通常工厂方法不采用 object 的类型来创建。 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.我不确定您将如何使用 generics 实现类似的功能,因为您需要在编译时提供通用参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM