0

好的.. C# 不是我的强项,我已经有一段时间没有开始研究这种事情了,我忘记了一些事情:我正在努力让这个也服从我:-) 我很确定我想要什么在 C# 中做是可能的,我很确定我的抽象和我的接口都是地狱(我什至不知道如何放入接口,但我知道我需要一个)

好的,这是场景

//abstract parent class
abstract class ActionType
{
    /***
     * this is a parent class not meant to ever be instaciated
     */
    public abstract void action();      
}

class ActionTypeSync : ActionType
{
    public override void action()
    {
        Debug.WriteLine("doing sync");
    }
}

class ActionTypeRead : ActionType
{
    public override void action()
    {
         Debug.WriteLine("doing read");
    }
}

以下不起作用

ActionType action = getActionType(1);
ActionType secondaction = getActionType(2);

[ 编辑 ]

实际上我说得太简短了,这一点没有出错

错误参数 1:无法从“ActionType”转换为“ActionTypeSync”

processThings(action);
//debug out put "doing sync"    
processThings(secondaction);
//debug out put "doing sync"   

public ActionType getActionType(int i)
{
     if (i==1) return new ActionTypeSync();
     if (i==2) return new ActionTypeRead();
}

public void processThings(ActionTypeSync action)
{
     action.action();
}

public void processThings(ActionTypeRead action)
{
     action.action();  
}

[/ 编辑 ]

我需要如何最好地重组这个..请理解这是一个简洁的例子(尽我所能)我在这里总结 - 所以有些原则比一些“为什么等等讲座”更好:-)谢谢你:-)我不反对为了适应多态原则而进行重组,但我需要这个基本的多态接口/类结构

4

1 回答 1

2

Overlooking your syntactical errors, this is doing exactly what you told it to do.

It is calling the local action() on the specific type you instantiated, it doesn't do anything else because you haven't told it to (i.e. at no stage are you calling base.action()).

Edit:

Based on your edit.... ActionTypeSync and ActionTypeRead can both be cast down to ActionType, but ActionType cannot be cast back up to either of those derived types. You can pass one of the derived objects around as an ActionType and the overridden action() method will be called, but you can't cast it implicitly or explicitly to the derived type. To fix this just change your method signatures:

public void processThings(ActionType action)
{
     action.action();
}

Because of this change you will now only need one method that will deal with both derived types because you have cast it down to its base type - IOW you can get rid of the processThings(ActionTypeRead action) method.

于 2012-11-21T22:13:36.827 回答