简体   繁体   English

将接口实例分配给实现该接口的类

[英]Assigning interface instance to a class that implements that interface

I have various classes that implements IActiveRecord. 我有各种实现IActiveRecord的类。

I want to have a method where I pass in a newly created class and assign ActiveRecord to the type of the class passed in. 我想要一种方法,可以传入新创建的类,然后将ActiveRecord分配给传入的类的类型。

I have tried the below but it does not compile for some reason. 我已经尝试了下面的方法,但是由于某种原因它没有被编译。

Any ideas? 有任何想法吗?

private void AddRecord<T>() where T : class, new()
        {

            IActiveRecord ActiveRecord = (IActiveRecord)T;
        }

Your question is unclear, but if I understand correctly what you are trying to do, you just need to add the constraint where T : IActiveRecord . 您的问题尚不清楚,但是如果我正确理解您要做什么,则只需where T : IActiveRecord添加约束。 Then you can say 那你可以说

void AddRecord<T>() where T : IActiveRecord, new() { 
    IActiveRecord activeRecord = new T();
    // more stuff
}

Regarding your line 关于你的线

IActiveRecord ActiveRecord = (IActiveRecord)T;

this is not legal. 这是不合法的。 T is a type parameter, not an expression that you can cast. T是类型参数,而不是您可以强制转换的表达式。

In the method you're displaying, you do not pass in an instance of a certain type ? 在您显示的方法中,您没有传入某种类型的实例吗? I do not really understand what you're trying to achieve. 我不太了解您要达到的目标。

Do you want to do this: 您要这样做吗?

private void AddRecord<T>() where T : IActiveRecord, new()
{
    IActiveRecord a = new T();
}

?

Looks like you want to constrain the generic type to be of type IActiveRecord , then you don't need the cast: 看起来您想将泛型类型限制为IActiveRecord类型,则不需要IActiveRecord

private void AddRecord<T>() where T : IActiveRecord, new()
{
    IActiveRecord a = new T();
}

I think you want to restrict your method by using the following: 我认为您想通过使用以下方法来限制您的方法:

private void AddRecord<T>() where T : IActiveRecord, new()

Otherwise, your question might not be clear to me. 否则,我可能不清楚您的问题。

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

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