Consider the following interface:

interface IToto
{
    string Name {get;}
}

Using Code Contracts, how can I make sure that the Name property value never changes?

I tried using Contract.OldValue within a ContractInvariantMethod-marked method but appearantly it isn't supported. Anything else I can do?

有帮助吗?

解决方案 2

Found my answer here. Appearantly it isn't yet supported by Code Contracts.

其他提示

This isn't possible using just interfaces. However, you can use an interface with an abstract class to get what you want. An abstract class allows you to define functionality but you cannot instantiate it. So in your real class you can inherit from the abstract class and you get your defined functionality automatically.

Take a look at this:

namespace ConsoleApplication1
{
    public interface IMyThing
    {
        string Name { get; }
    }

    public abstract class MyThingBase : IMyThing
    {
        public string Name {
            get
            {
                return "Mystringvalue";
            }
        }
    }

    public class MyThing : MyThingBase
    {
        //stuff
    }
}

Then:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var myObject = new MyThing();

            Console.Write(myObject.Name);
        }
    }
}

This prints: Mystringvalue

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top