简体   繁体   中英

C# initialization question

This might be lame, but here:

public interface Interface<T>
{
    T Value { get; }
}

public class InterfaceProxy<T> : Interface<T>
{
    public T Value { get; set; }
}

public class ImplementedInterface: InterfaceProxy<Double> {}

Now I want to create an instance of the ImplementedInterface and initialize it's members.

Can this be done somehow like this (using initialization lists) or the same behavior can only be achieved using the constructor with Double argument?

var x = new ImplementedInteface { 30.0 };

可以通过以下方式完成:

var x = new ImplementedInteface { Value = 30.0 };

您应该能够:

var x = new ImplementedInterface {Value = 30.0};
var x = new ImplementedInterface() { Value = 30.0 };

The only way to achieve what you're after is if your class implements IEnumerable<T> and has an Add method:

public class MyClass : IEnumerable<double>
{
   public void Add(double x){}
}

Then you can do:

MyClass mc = new MyClass { 20.0 };

Obviously that's not what you want, because that doesn't set your Value and it allows you to add multiple values:

MyClass mc = new MyClass { 20.0, 30.0 , 40.0 };

Just go with the standard object initializes like others have pointed out:

var x = new ImplementedInterface() { Value = 30.0 };

var instance = new ImplementedInterface { Value = 30.0 }; will work. However, this isn't really the same set of operations as C++ initializer lists -- this is an object initializer. It initializes the new instance via the default constructor and then invokes the property setters for each property.

In other words, the object is constructed before the property setters run. If you want the values for the properties set before construction of ImplementedInterface completes, you'd have to write a constructor, as you noted. This distinction in behavior usually doesn't matter, but it's good to be aware of.

I am not sure if you have a special reason to use the interfaces that way but the following code might work for you.

public class ImplementedInterface2 : List<double> { }

 public class test
    {
        public void x()
        {
            var x = new ImplementedInterface2() { 30.0 };
        }
    }
var x = new ImplementedInterface { Value = 30.0 };

您绝对可以使用初始化列表,但是必须指定30.0是什么(对于任何初始化列表都是如此,而不仅仅是您拥有的代码):

var x = new ImplementedInteface { Value=30.0 };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM