泛型无法显式转换类型

时间:2018-04-30 00:10:53

标签: c# generics

对于后台我主要用Java编程,我正在尝试使用/学习C#项目中的泛型并陷入困境。

这是我的问题。从主要方法你可以看到我正在尝试设置士兵任务,但我收到错误,

cannot convert from 'TaskHeal' to 'TaskBase<SoldierBase>'

看起来这个演员应该工作,因为TaskHeal是TaskBase的孩子,但事实并非如此。这是我的完整代码:

public class Main {
    static void main(string[] args) {
        SoldierMedic myMedic = new SoldierMedic();
        myMedic.setTask(new TaskHeal(myMedic)); // Problem!
    }
}


public class SoldierBase {

    private TaskBase<SoldierBase> currentTask;
    public int status;

    public void setTask(TaskBase<SoldierBase> newTask) {
        this.currentTask = newTask;
    }
}


public class SoldierMedic : SoldierBase {
    public int healRate = 45;
}


public abstract class TaskBase<T> where T : SoldierBase {

    protected T soldier;

    public TaskBase(T unit) {
        this.soldier = unit;
        this.soldier.status = 1;
    }

    public abstract void preformTask();
}


public class TaskHeal : TaskBase<SoldierMedic> {

    public TaskHeal(SoldierMedic unit) : base(unit) { }

    public override void preformTask() {
        this.soldier.healRate++;
    }
}

1 个答案:

答案 0 :(得分:3)

如果您不介意为library(dplyr) library(purrr) df_list %>% map(. %>% mutate(County = case_when( Zip >= 44056 & Zip <= 44356 ~ "Summit", Zip >= 1300 & Zip <= 13035 ~ "Madison", Zip < 1300 | Zip > 13036 ~ "Micoded", TRUE ~ NA_character_))) # $NY # State Zip County # 1 NY 13035 Madison # 2 NY 13035 Madison # 3 NY 13056 Micoded # # $OH # State Zip County # 1 OH 44141 Summit # 2 OH 44056 Summit # 3 OH 44131 Summit TaskBase添加额外的基础,非通用类,则可以执行以下操作:

SoldierBase

如果你希望它看起来更像c#(使用属性,正确的访问修饰符和套管),你可以这样做:

class Program
{
    static void Main(string[] args)
    {
        var myMedic = new SoldierMedic();
        myMedic.setTask(new TaskHeal(myMedic)); // Problem!
    }
}

public class SoldierBase
{
    public int status;
}

public class SoldierBase<T> : SoldierBase where T : SoldierBase
{
    private TaskBase currentTask;

    public void setTask(TaskBase newTask)
    {
        this.currentTask = newTask;
    }
}

public class SoldierMedic : SoldierBase<SoldierMedic>
{
    public int healRate = 45;
}

public abstract class TaskBase
{

}

public abstract class TaskBase<T> : TaskBase where T : SoldierBase<T>
{
    protected T soldier;

    public TaskBase(T unit)
    {
        this.soldier = unit;
        this.soldier.status = 1;
    }

    public abstract void preformTask();
}


public class TaskHeal : TaskBase<SoldierMedic>
{

    public TaskHeal(SoldierMedic unit) : base(unit) { }

    public override void preformTask()
    {
        this.soldier.healRate++;
    }
}