2013-03-18 47 views
6

我在獲取該通用約束條件時遇到了一些麻煩。定義值類型和引用類型的通用接口類型約束條件

我有兩個接口如下。

我想限制ICommandHandlers TResult類型只使用實現ICommandResult的類型,但是ICommandResult有自己的需要提供的約束。 ICommandResult可能會從其Result屬性返回值或引用類型。我錯過了明顯的東西嗎?謝謝。

public interface ICommandResult<out TResult> 
{ 
    TResult Result { get; } 
} 

public interface ICommandHandler<in TCommand, TResult> where TCommand : ICommand 
                 where TResult : ICommandResult<????> 
{ 
    TResult Execute(TCommand command); 
} 
+0

我看不到這與引用類型和值類型有什麼關係 – 2013-03-18 10:20:49

+0

ICommandResult Result屬性可以是值類型或引用類型。 – Matt 2013-03-18 10:24:13

+0

所以可以使用任何其他泛型類型,除非受到「where T:class/struct」 ? – 2013-03-18 10:28:11

回答

1

你可以改變你的界面的(這看起來有點清潔劑給我):

public interface ICommandHandler<in TCommand, TResult> where TCommand : ICommand 
{ 
    ICommandResult<TResult> Execute(TCommand command); 
} 

或者你也可以添加類型參數ICommandResult<TResult>到您的通用參數列表:

public interface ICommandHandler<in TCommand, TCommandResult, TResult> 
    where TCommand : ICommand 
    where TCommandResult: ICommandResult<TResult> 
{ 
    TCommandResult Execute(TCommand command); 
} 
+0

謝謝,我認爲您的第一個選項是最優雅的。 – Matt 2013-03-18 10:25:08

0

你可以第3泛型類型參數添加到ICommandHandler:更多

public interface ICommandResult<out TResult> 
{ 
    TResult Result { get; } 
} 

public interface ICommandHandler<in TCommand, TResult, TResultType> 
                 where TCommand : ICommand 
                 where TResult : ICommandResult<TResultType> 
{ 
    TResult Execute(TCommand command); 
} 
0

嗯,應該不是你的第二個界面這個樣子的?

public interface ICommandHandler<in TCommand, ICommandResult<TResult>> 
    where TCommand : ICommand 
{ 
    TResult Execute(TCommand command); 
} 
+0

'out' there?我相信這是不可能的! – 2013-03-18 10:09:57

+0

這是我不確定的部分。我目前正在使用.Net 3.5 ...我將刪除它。 – DHN 2013-03-18 10:10:36

+0

您可以定義參數在接口定義中是逆向的:D – 2013-03-18 10:11:21

0

這應做到:

public interface ICommandHandler<in TCommand, out TResult> 
    where TCommand : ICommand 
    where TResult : ICommandResult<TResult> 
{ 
    TResult Execute(TCommand command); 
}