Skip to main content
 首页 » 编程设计

c#之尝试转换为泛型类型时出错 : redundant cast

2024年02月05日15kerrycode

我有一个通用函数,它返回 AnyListVM 的子类的新实例,基本上是这样实现的:

    public TListVM MakeListVM<TListVM>() 
        where TListVM : AnyListVM 
    { 
        TListVM listVM; 
        switch(typeof(TListVM).ToString()) 
        { 
            case nameof(EventListVM): 
                listVM = new EventListVM(); 
                // some more init stuff 
                break; 
 
            // some more similar cases 
 
            default: 
                throw new NotImplementedException(); 
        } 
        return listVM; 
    } 

两个涉及的类目前看起来像这样,还没有任何有意义的实现:

public abstract class AnyListVM 
{ 
} 
 
public class EventListVM : AnyListVM 
{ 
} 

现在 Visual Studio 在我的 new EventListVM() 下划线并提醒说它不能将 EventListVM 隐式转换为 TListVM。

好吧,所以我想我只是添加一个显式转换:

        listVM = (TListVM)new EventListVM(); 

但是没有。现在 Visual Studio 再次强调它并说它是一个多余的转换。提供的自动修复将再次删除类型转换。无限循环。

这里出了什么问题,为什么我不允许显式或隐式地执行此转换?

请您参考如下方法:

您的实现中有一件明显的错误,其他人已经指出但没有令人满意地解决。如果您打算实例化 TListVM,那么您需要更改两个非常重要的部分。首先是新的代码 list :

public TListVM MakeListVM<TListVM>() 
    where TListVM : AnyListVM, new() 
{ 
    TListVM listVM = new TListVM(); 
 
    EventListVM evtList = listVM as EventListVM; 
    if (evtList != null) 
    { 
        // set evtList properties.  You can't change 
        // the instantiation method. 
    } 
 
    // repeat for other constructs. 
 
    return listVM; 
} 

现在稍微解释一下。通用 where 子句需要指定您打算使用无参数构造函数创建 TListVM。为此,您需要将 new() 指定为通用约束。

这极大地简化了你的实现,它只知道有一个叫做 TListVM 的东西,它有一个基类 AnyListVM 并且有一个没有参数的构造函数。不需要复杂的 switch 语句,也不需要使用 Activator。

在处理泛型时,请直接使用泛型参数。


根据进一步的信息,switch 语句仍然是错误的工具。泛型必然会限制您使用对象的方式。您无法更改构造函数,但可以专门化对象实例化后设置属性的方式。

上面我更改了 list 以显示如何直接设置这些属性。

相反,如果您执意要使用不同的构造函数等,那么您将不得不采用不同的方法。您将必须返回基类并且不是TListVM。

public AnyListVM MakeListVM<TListVM>() 
    where TListVM : AnyListVM 
{ 
    return MakeListVM(typeof(TListVM)) as TListVM; 
} 
 
private AnyListVM MakeListVM(Type listVM) 
{ 
    AnyListVM listVM; 
    switch(listVM.ToString()) 
    { 
        case nameof(EventListVM): 
            listVM = new EventListVM(); 
            // some more init stuff 
            break; 
 
        // some more similar cases 
 
        default: 
            throw new NotImplementedException(); 
    } 
    return listVM; 
} 

通用帮助器方法让您包装更通用的工厂方法,使其具有您想要的签名,而不会导致编译错误。