gpt4 book ai didi

c# - ViewModelBuilder 泛型类型转换问题

转载 作者:太空狗 更新时间:2023-10-29 23:08:31 27 4
gpt4 key购买 nike

<分区>

绞尽脑汁也无济于事,不知道有没有人能帮上忙?

遇到一个非常令人沮丧的转换问题,我肯定会很快得到答案,但由于我对泛型类型推断或其他东西的理解有限,这可能只是发生了。

提前致谢!

场景是向导站点的多个“步骤”ViewModel。我正在为每个创建生成器类,并使用工厂为返回给我的步骤获取特定的生成器,这是 IStepViewModel 的集合。

public interface IStepViewModelBuilderFactory
{
IStepModelBuilder<T> Create<T>(T stepViewModel) where T : IStepViewModel;
void Release<T>(IStepModelBuilder<T> stepViewModelBuilder) where T : IStepViewModel;
}

public interface IStepViewModel
{
}

public interface IStepModelBuilder<TStepViewModel> : IModelBuilder<TStepViewModel> where TStepViewModel : IStepViewModel
{
}

public class SpecificViewModelBuilder : IStepModelBuilder<SpecificStepViewModel>
{
}

public class SpecificStepViewModel: StepViewModel
{
}

public abstract class StepViewModel : IStepViewModel
{
}

失败的测试!

[Test]
public void TestResolution()
{
var factory = this.container.Resolve<IStepViewModelBuilderFactory>();

IStepViewModel viewModel = new SpecificStepViewModel();

var builder = factory.Create(viewModel); // Here

Assert.That(builder, Is.Not.Null);
}

问题!

Unable to cast object of type 'Company.Namespace.SpecificViewModelBuilder ' to type 'Company.Namespace.Builders.IStepModelBuilder`1[Company.Namespace.IStepViewModel]'.

Factory Impl 如下使用 CaSTLe.Windsor

public class StepViewModelSelector : DefaultTypedFactoryComponentSelector
{
protected override Type GetComponentType(System.Reflection.MethodInfo method, object[] arguments)
{
var arg = arguments[0].GetType();
var specType = typeof(IModelBuilder<>).MakeGenericType(arg);
return specType;
}
}

这个的注册:

container.AddFacility<TypedFactoryFacility>();

....

container
.Register(
Classes
.FromAssemblyContaining<StepViewModelSelector>()
.BasedOn<StepViewModelSelector>());

container
.Register(
Component
.For<IStepViewModelBuilderFactory>()
.AsFactory(c => c.SelectedWith<StepViewModelSelector>()));

堆栈跟踪:

System.InvalidCastException was unhandled by user code
HResult=-2147467262 Message=Unable to cast object of type 'Company.Namespace.SpecificViewModelBuilder' to type 'Company.Namespace.IStepModelBuilder`1[Company.Namespace.IStepViewModel]'. Source=DynamicProxyGenAssembly2 StackTrace: at Castle.Proxies.IStepViewModelBuilderFactoryProxy.Create[T](T stepViewModel) at Tests.Infrastructure.ViewModelBuilderFactoryTests.TestResolution() in c:\Project\Infrastructure\ViewModelBuilderFactoryTests.cs:line 61
InnerException:

编辑:IModelBuilder<T>界面

public interface IModelBuilder<TViewModel>
{
TViewModel Build();
TViewModel Rebuild(TViewModel model);
}

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com