相关疑难解决方法(0)

C#创建新T()

你可以看到我正在尝试(但没有)使用以下代码:

protected T GetObject()
{
    return new T();
}
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激.

编辑:

背景如下.我正在使用标准化方法为所有控制器提供自定义控制器类.所以在上下文中,我需要创建一个控制器类型对象的新实例.所以在撰写本文时,它是这样的:

public class GenericController<T> : Controller
{
    ...

    protected T GetObject()
    {
        return (T)Activator.CreateInstance(ObjectType);
    }        

    public ActionResult Create()
    {
        var obj = GetObject()

        return View(obj);
    }
Run Code Online (Sandbox Code Playgroud)

所以我决定这里的反思最简单.我同意,当然在给出问题的初始陈述时,标记为正确的最合适的答案是使用new()约束的答案.我已经修好了.

.net c# generics .net-4.0 c#-4.0

146
推荐指数
7
解决办法
13万
查看次数

通用类型的强制转换失败

我无法将泛型类型转换为另一种泛型类型,除了转换应该是有效的

我想要归档的是简短的(用于MyModel实现IModelMyImplementation实现IImplementation):

IImplementation<IModel> implementation = new MyImplementation<MyModel>();
Assert.IsNull(implementation as IImplementation<IModel>);
Run Code Online (Sandbox Code Playgroud)

这有点令人困惑,因为类型应该是有效的.

完整的概念模型:

interface IModel {}

class MyModel : IModel {}

interface IImplementation<TModel> where TModel : IModel { }

class MyImplementation<TModel> : IImplementation<TModel>
    where TModel : IModel { }

public void CallRegister()
{
    var implementation = new MyImplementation<MyModel>();
    var instance = CastModel(implementation);
    Assert.IsNotNull(instance); //this assert fails!
}

private object CastModel<TModel>(IImplementation<TModel> implementation) where TModel : IModel
{
    return implementation as IImplementation<IModel>;
}
Run Code Online (Sandbox Code Playgroud)

我需要这个强制转换才能让我将多个IImplementation …

c# generics casting

3
推荐指数
2
解决办法
496
查看次数

标签 统计

c# ×2

generics ×2

.net ×1

.net-4.0 ×1

c#-4.0 ×1

casting ×1