检测通用类型中的接口

kim*_*3er 1 c# generics interface constraints

我有一个方法:

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

        AddToCacheUsingKey(value);
    }
Run Code Online (Sandbox Code Playgroud)

我想根据value参数的实现选择性地调用以下方法IIDModel.

    public void Store<T>(T value) where T : class, IIDModel, new() {
        AddModelToCache(value);
    }
Run Code Online (Sandbox Code Playgroud)

有没有办法告诉Store<T>value从参数StoreUsingKey<T>工具IIDModel?或者我是以错误的方式来做这件事的?

丰富

回答

new()从每个方法中删除约束允许代码工作.问题在于我试图将接口作为可以实例化的对象传递出去.

BFr*_*ree 5

你已经是.通过将IIDModel约束放在Store <T>方法上,您可以保证value参数实现IIDModel.

哦,好的,我现在看到你在说什么.这个怎么样:

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

                AddToCacheUsingKey(value);
        }
Run Code Online (Sandbox Code Playgroud)

再次编辑: Tinister是对的.这本身不会起作用.但是,如果您的Store方法看起来像Joel Coehoorn发布的那样,那么它应该可行.