繁体   English   中英

为什么MakeGenericType会在创建的类型中添加反引号?

[英]why does MakeGenericType put a backtick in the type it creates?

因此,我将介绍“ ASP.NET MVC 2 In Action”一书中的演示。 并非出于任何真正的原因而玩。 我试图用一个真正的IOC容器实现一个示例(它们在示例代码中使用的是伪造的,当然可以工作)。 我遇到的问题是MakeGenericType返回名称中带有反勾号1的怪异类型。 我看着这个问题,在Visual Studio调试器中,类型名称中的反引号是什么意思? 似乎暗示它仅用于显示目的? 但事实并非如此。 这是我的代码。

//here are the ways I tried to register the types
 private static void InitContainer()
 {
     if (_container == null)
     {
         _container = new UnityContainer();
     }
     _container.RegisterType<IMessageService, MessageService>();
     _container.RegisterType<IRepository, Repository>();
     _container.RegisterType(typeof(IRepository<Entity>), typeof(Repository<Entity>));
  }

这是我尝试实现的模型绑定程序中的代码。

public class EntityModelBinder: IFilteredModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        ValueProviderResult value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (value == null)
            return null;
        if (string.IsNullOrEmpty(value.AttemptedValue))
            return null;
        int entityId;
        if (!int.TryParse(value.AttemptedValue, out entityId))
            return null;
        Type repoType = typeof (IRepository<>).MakeGenericType(bindingContext.ModelType);
        var repo = (IRepository)MvcApplication.Container.Resolve(repoType, repoType.FullName, new ResolverOverride[0]);
        Entity entity = repo.GetById(entityId);
        return entity;
    }

    public bool IsMatch(Type modelType)
    {
        return typeof (Entity).IsAssignableFrom(modelType);
    }
}

对container.resolve的调用始终会因以下错误而崩溃:

依赖关系的解析失败,类型=“ MvcModelBinderDemo.IRepository`1 [MvcModelBinderDemo.Entity]”,名称=“ MvcModelBinderDemo.IRepository`1 [[MvcModelBinderDemo.Entity,MvcModelBinderDemo,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null ]]”。 发生以下异常:正在解决。

另外-我确实知道将ref放到ModelBinder中的MvcApplication有点草率,只是试图弄清楚事物是如何工作的以及到达容器的需要。

感谢您的任何投入。

我认为问题在于您在Resolve中明确指定了名称。 尝试删除第二个参数repoType.FullName

尝试使用MvcApplication.Container.Resolve(repoType); 不要忘记using Microsoft.Practices.Unity;添加using Microsoft.Practices.Unity; 在* .cs文件的顶部。

反引号的含义已在您链接的问题中得到解答。 但是,您的结论不正确。 它不仅用于显示目的。 带有反引号的名称是您的类的CLR名称。
那不是问题的根源。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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