具有对象初始值设定项和属性的接口/IDisposable

Interface / IDisposable with Object Initializers and Properties

作为在

回答的问题的跟进

如何使用具有接口结构的对象初始值设定项和属性:

public class SomeClassHelper : ISomeClassHelper 
{
}

public class SomeClass: IDisposable
{
    public SomeClass(object somevalue) {
    }

    public int AnotherValue { get; set; }

    public int AdditionalValue { get; set; }

    internal void ImHere() {
        throw new NotImplementedException();
    }

    public void Dispose() {
        throw new NotImplementedException();
    }
}

static void Main(string[] args) {
    object somevalue = null;
    using (var something = new SomeClass(somevalue) { AnotherValue = 1, AdditionalValue = 2 }) {
        something.ImHere();
    }
}

我将如何使用上面的内容才能拥有接口,或者接口的目的是否破坏了上面的内容?

我认为您可能误解了接口的用途。

来自https://msdn.microsoft.com/en-us/library/ms173156.aspx

An interface contains definitions for a group of related functionalities that a class or a struct can implement. By using interfaces, you can, for example, include behavior from multiple sources in a class. That capability is important in C# because the language doesn't support multiple inheritance of classes. In addition, you must use an interface if you want to simulate inheritance for structs, because they can't actually inherit from another struct or class.

接口是强制任何实现它的 class 满足特定条件,以便其他代码可以依赖于该 class 与任何其他 class 具有某些共性实现相同的界面。

所以在你的另一个问题中,人们已经回应建议如果你想使用 using 块,你的 class 需要实现 IDisposable 接口。这是因为,要使 using 工作,它需要知道它正在使用的 class 将有一个名为 Dispose() 的方法,该方法释放class.

使用

如果您的 SomeClass 没有任何非托管资源,重新审视您正在尝试做的事情可能是明智的。垃圾收集器将在托管对象(如您的 class 的实例)停止使用时自动处理它们(我在这里概括了一下)。

你的其他问题确实应该回答这个问题,但你可能想探索做的事情(而不是使用初始化程序)是为你的 class 创建一个构造函数,并在以下情况下使用它实例化你的 class.

您最终会得到如下内容:

    public class SomeClass: IDisposable
    {
        public SomeClass(object somevalue, int anotherValue, int additionalValue)
        {
            AnotherValue = anotherValue;
            AdditionalValue = additionalValue;
        }

        public int AnotherValue { get; set; }

        public int AdditionalValue { get; set; }

        internal void ImHere()
        {
            throw new NotImplementedException();
        }

        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }

    static void Main(string[] args)
    {
        object somevalue = null;
        using (var something = new SomeClass(somevalue, 1, 2))
        {
            something.ImHere();
        }
    }

您可以在 https://msdn.microsoft.com/en-us/library/ms173115.aspx 阅读更多关于使用构造函数的信息。