Задайте вопросЗадайте вопрос
 

ОтвеченоHow do I put a contract on a generic interface?

  • 26 февраля 2009 г. 11:33OpinionatedGeek Медали пользователяМедали пользователяМедали пользователяМедали пользователяМедали пользователя
     С кодом
    Say I have the following interface:

    public interface IParser<T>
    {
        T Parse (
    string toParse);
    }

    How do I specify the attributes for the contract class?

    My initial thought was:

    [ContractClass (typeof (IParserContract<T>))]
    public interface IParser<T>
    {
        T Parse (
    string toParse);
    }

    and

    [ContractClassFor (typeof (IParser<T>))]
    public class IParserContract<T>
    {
        ...
    }

    But that won't work, because you can't use the generic T argument in the attributes.  And leaving the generic argument out won't work, because that doesn't specify the right interface/type.

    So, am I missing the proper way of doing this, or is this a limitation?

    Cheers,

        Geoff

Ответы

  • 26 февраля 2009 г. 15:26Manuel FahndrichMSFT, ВладелецМедали пользователяМедали пользователяМедали пользователяМедали пользователяМедали пользователя
     ОтвеченоС кодом
    Excellent question and we probably should put this into the documentation. For generic interface contracts, the typeof has to refer to the non-instantiated generic type. This is a little known C# feature. It looks as follows:

    [ContractClass (typeof (IParserContract<>))]  
    public interface IParser<T>  
    {  
        T Parse (string toParse);  
    }  
     
    [ContractClassFor (typeof (IParser<>))]  
    public class IParserContract<T>  
    {  
        ...  
    }  
     
     

    Note the empty instantiation brackets IParserContract<> and IParser<>.

    -MaF

Все ответы