有一种逆操作吗?

时间:2010-09-13 17:38:46

标签: c# reflection

我得到了Type,但这与我正在寻找的Class不同。

是否存在typeof的反向操作?

修改

我需要这个类才能使用通用存储库:

GenericRepository<BaseEntity> repository = new GenericRepository<BaseEntity>(new AzureBrightData());

我从编写BaseEntity开始,所有实体类都从该BaseEntity下降,但问题是存储库需要知道要搜索哪个表。

例如,如果我们有(1,1)的分区键和行键组合对,则不允许我或存储库知道从哪个表获取注册表。这还不够,这就是为什么我相信我需要这张桌子。

8 个答案:

答案 0 :(得分:7)

如果我理解你问题的答案,那么你可能正在寻找类似的东西(实例化类型):

     Assembly asmApp = Assembly.LoadFile("some.dll");
     Type tApp = asmApp.GetType("Namespace.SomeClass");
     object oApp = Activator.CreateInstance(tApp, new object[0] { });

答案 1 :(得分:3)

使用“Activator”类:

Activator.CreateInstance<T>

答案 2 :(得分:2)

我认为您正在寻找Activator.CreateInstance

答案 3 :(得分:2)

我的答案基于您在评论中提供的澄清:

  

我误解了每个人在这里所说的话,或者至少我没有说清楚。我想要上课,因为我会正常使用它。例如,我必须像这样传递类:public void methodName<T>()其中T是类。

简短回答:不,你不能,因为泛型类型在编译时被解析。

答案很长:是的,你可以,但你需要使用反射。这是你如何做到的:

答案 4 :(得分:1)

使用new()约束。

public T Create<T>() where T : new() {
    return new T();
}

答案 5 :(得分:1)

以下是按照我的偏好列出的一些选项。我假设T是泛型类或方法中的类型参数。

new T(); // T must be constrained to support a default constructor.

Activator.CreateInstance(typeof(T), new object[] { });

typeof(T).GetConstructor(new Type[] { }).Invoke(null);

AppDomain.CurrentDomain.CreateInstanceAndUnwrap(typeof(T).Assembly.FullName, typeof(T).FullName);

答案 6 :(得分:1)

我一定错过了什么。到目前为止提供的答案似乎与问题不符。我希望更清晰。

尽管如此,我会尽力回答这个问题。

你说你正试图这样做:

var repository = new GenericRepository<BaseEntity>(new AzureBrightData());

你想尝试做更像这样的事吗?

var repository = new GenericRepository<AzureBrightData>();

如果是这样,那么您的通用存储库类需要定义如下:

public class GenericRepository<T> where T : BaseEntity, new()
{
    ...
}

然后你可以像以前那样定义你的BaseEntity类,但是你的存储库的实例化将为你提供实际的类 - 我希望那个表 - 你正在寻找。

我希望我理解你的问题。

答案 7 :(得分:0)

我不完全理解 OP 问题,但我认为这肯定会帮助一些搜索 inverse of typeof 的人,这就是我自己来到这里的方式。

我在查找表中有一个动态组件列表。

class ImageComponent
{
    media: 'IMAGE';
}
  
class VideoComponent
{
    media: 'VIDEO';
}

// lookup table (runtime construct)    
const components = {

    'image': ImageComponent,
    'video': VideoComponent
}

所以我想取 'image'(表中的键)并最终得到 IMAGE,它是 ImageComponent 的一个属性。

从表中查找组件:

type imageComponent = typeof components['image'];    // typeof ImageComponent
   

如果我们确实有 ImageComponent,那么我们可以对其进行类型查找。

ImageComponent['media']       // 'IMAGE'

但是我们有 typeof ImageComponent 而不是用于查找类的任何属性。

 type mediaType = imageComponent['media'];                // does not work

实际答案...

所以我们可以做的是从`typeof YourClassName 中获取'原型类型'。

  type media = imageComponent['prototype']['media'];      // 'IMAGE'  (const value)

或者换句话说,我们实际上在做的是:

  type media = (typeof ImageComponent)['prototype']['media'];

所以对我来说,这满足了我对“inverse of typeof”的搜索。

另请注意,'IMAGE''VIDEO'literal types 而不是字符串(除非在运行时它们只是字符串)。

相关问题