我想创建一个通用的查找方法,指定一种类型的对象和一些其他识别参数,该方法返回该类型的对象。这可能吗?
我在想这样的事情。
public T GetObjectOfType(Guid ID, typeof(T Class))
{
//lookup this object and return it as type safe
}
我知道这不起作用,但我希望它能解释这个概念
答案 0 :(得分:2)
您可以使用通用方法:
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;
}
如果你想要的只是创建一个特定类型的实例,你不需要额外的id参数,我假设你想根据id设置一些属性等。此外,您的类必须提供默认构造函数,因此new()
约束。
答案 1 :(得分:2)
通常,工厂方法不会创建对象类型。它们返回一个实现某个公共接口的类型,而具体的底层类型依赖于某个参数,通常是枚举值。一个简单的例子:
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 );
}
}
你有类型安全。我不确定如何在编译时使用泛型实现类似的东西。