泛型的很多我的問題,我希望它仍然是可以理解的......通用接口,通用接口與泛型
我有以下接口:
public interface ICommandBus
{
TResult Publish<TCommand, TResult>(TCommand command)
where TResult : ICommandResult
where TCommand : ICommand<TResult>;
}
public interface ICommand<T>
where T : ICommandResult
{ }
public interface ICommandResult
{
bool Success { get; }
}
,我想用它們的實現這種方式(我ommit的CommandBus,它不是有用的這個問題,但你可以找到它here):我的錯誤
public class CreateItemCommand: ICommand<CreateItemResult>
{
public string Name { get; private set; }
}
public class CreateItemResult: ICommandResult
{
public bool Success { get; private set; }
}
var command = new CreateItemCommand();
var result = commandBus.Publish(command); //Error here
:The type arguments cannot be inferred from the usage
。 我試過的東西與in和out修飾符沒有成功...
我怎麼能說我的Publish
方法,wihout指定的參數類型是這樣的:
var result = commandBus.Publish<CreateItemCommand, CreateItemResult>(command); //Works, but ugly...
編輯:更新盧卡斯回答
盧卡斯解決方案應該工作,但我仍然必須把where TResult : ICommandResult
約束,以避免錯誤There is no boxing conversion or type parameter conversion from 'TResult' to 'Core.Command.ICommandResult'
。
我也有繼承一個巨大的問題,比方說,我有以下的抽象CommandObserver:
public abstract class NotificationObserver<TResult> : ICommandObserver<TResult>
where TResult : ICommandResult
{
protected virtual bool IsEnable(ICommand<TResult> command, TResult result)
{
return true;
}
}
而且它的實現
public class CreateItemObserver : NotificationObserver<CreateItemResult>
{
protected override bool IsEnable(CreateItemCommand command, CreateItemResult result)
{
return !String.IsNullOrEmpty(command.Name);
}
}
這是行不通的,因爲實現不確實會覆蓋虛擬方法(不同的簽名:ICommand<TResult>
!= CreateItemCommand
)。
如果我去做保持正確的簽名,我不能沒有一個醜陋投在實現中使用CreateItemCommand屬性...
所有泛型的要點是什麼?似乎反作用有泛型和專業化的一些接口... –
我認爲這是重點...我濫用泛型,現在我卡... – jbuiss0n
在編輯中的後續問題是它自己的問題,所以你應該單獨張貼它,如果你想它的答案。你試圖在這裏做一個雙重調度,也許你應該試試[訪問者模式](http://en.wikipedia.org/wiki/Visitor_pattern)。 – Falanwe