0

メソッドを実装していますSystem.IServiceProvider.GetServiceが、警告を抑制できません... implements interface method 'System.IServiceProvider.GetService(System.Type)', thus cannot add Requires.

[SuppressMessage("Microsoft.Contracts","CC1033", Justification="Check to require service type not null cannot be applied")]
public object GetService(Type serviceType)
{
}
4

1 に答える 1

0

GetService具象クラスに実装したインターフェースのメソッドであり、具象クラスのメソッドにはコントラクトが含まれていると思います。このコントラクトは、インターフェイスのコントラクトを提供するコントラクトクラスに移動する必要があります。詳細については、コードコントラクトのドキュメント(セクション2.8)を参照してください。以下は抜粋です。

ほとんどの言語/コンパイラ(C#およびVBを含む)ではメソッド本体をインターフェイス内に配置できないため、インターフェイスメソッドのコントラクトを作成するには、それらを保持するための個別のコントラクトクラスを作成する必要があります。

インターフェイスとそのコントラクトクラスは、属性のペアを介してリンクされます(セクション4.1)。

[ContractClass(typeof(IFooContract))]
interface IFoo
{
    int Count { get; }
    void Put(int value);
}

[ContractClassFor(typeof(IFoo))]
abstract class IFooContract : IFoo
{
    int IFoo.Count
    {
        get
        {
            Contract.Ensures( 0 <= Contract.Result<int>() );
            return default( int ); // dummy return
        }
    }
    void IFoo.Put(int value)
    {
        Contract.Requires( 0 <= value );
    }
}

これを行わない場合は、警告を抑制するには、コードコントラクトが適用されていないため、コードコントラクトを削除するだけです。

アップデート

これは機能しているように見えるテストケースです。

namespace StackOverflow.ContractTest
{
    using System;
    using System.Diagnostics.Contracts;

    public class Class1 : IServiceProvider
    {
        public object GetService(Type serviceType)
        {
            Contract.Requires<ArgumentNullException>(
                serviceType != null,
                "serviceType");
            return new object();
        }
    }
}

namespace StackOverflow.ContractTest
{
    using System;

    using NUnit.Framework;

    [TestFixture]
    public class Tests
    {
        [Test]
        public void Class1_Contracts_AreEnforced()
        {
            var item = new Class1();
            Assert.Throws(
                Is.InstanceOf<ArgumentNullException>()
                    .And.Message.EqualTo("Precondition failed: serviceType != null  serviceType\r\nParameter name: serviceType"),
                () => item.GetService(null));
        }
    }
}

これはあなたのシナリオとは違うことをしていますか?

于 2013-01-02T22:06:36.530 に答える