简体   繁体   中英

Detecting Interfaces in Generic Types

I have a method:

    public void StoreUsingKey<T>(T value) where T : class, new() {
        var idModel = value as IIDModel;
        if (idModel != null)
            Store<T>(idModel);

        AddToCacheUsingKey(value);
    }

that I would like to optionally call the following method, based on the value parameter's implementation of IIDModel .

    public void Store<T>(T value) where T : class, IIDModel, new() {
        AddModelToCache(value);
    }

Is there a way to tell Store<T> that the value parameter from StoreUsingKey<T> implements IIDModel ? Or am I going about this the wrong way?

Rich

Answer

Removing the new() constraint from each method allows the code to work. The problem was down to me trying to pass off an interface as an object which can be instantiated.

You already are. By putting the IIDModel constraint on the Store<T> method, you're guaranteeing, that the value parameter implements IIDModel.

Oh, ok I see what you're saying now. How about this:

public void StoreUsingKey<T>(T value) where T : class, new() {
                if (idModel is IIDModel)
                        Store<T>((IIDModel)idModel);

                AddToCacheUsingKey(value);
        }

Edit yet again: Tinister is right. This by itself won't do the trick. However, if your Store method looks like what Joel Coehoorn posted , then it should work.

public void Store(IIDModel value) {
    AddModelToCache(value);
}

Removing the new() constraint from each method allows the code to work. The problem was down to me trying to pass off an interface as an object which can be instantiated.

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