开发者

Assigning interface instance to a class that implements that interface

I have various classes that implements IActiveRecord.

I want to have a me开发者_如何学编程thod where I pass in a newly created class and assign ActiveRecord to the type of the class passed in.

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. 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.


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:

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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜