简体   繁体   中英

Assigning interface instance to a class that implements that interface

I have various classes that implements 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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