C#相关的构造函数和属性 [英] C# related on Constructor and Property
问题描述
我正在构建一些小的lib,我遇到了一个问题。
我想提供一个双向的解决方案,例如:
I am building some tiny lib, and I have run into a problem. I want to provide a two-way solution, for example:
我该如何做到这一点?
我得到异常抛出,因为它期望的东西...任何例子,会做是欢迎:)谢谢!
How can I accomplish this? I am getting exception thrown, because it expects something... Any example that will do is welcomed :) Thanks!
编辑:我正在执行某项,最初我的代码与此类似:
I am executing something, initially my code is similar to this one:
System.IO.DriveInfo d = new System.IO.DriveInfo("C:");
我想使用我的类实现以下操作:
I want to achieve with my class the following:
Driver d = new Driver();
d.DriverLetter = "C:";
仍然得到相同的结果,我使用ManagementObjectSearch,ManagementObjectCollection和一些其他System.Management类。
And still get the same results, I use ManagementObjectSearch, ManagementObjectCollection and some other System.Management classes.
推荐答案
您需要提供两个构造函数:
You need to provide both constructors:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Country { get; set; }
// Paramterless constructor - for new Person();
// All properties get their default values (string="" and int=0)
public Person () { }
// Parameterized constructor - for new Person("Joe", 16, "USA");
public Person (string name, int age, string country)
{
Name = name;
Age = age;
Country = country;
}
}
如果定义了参数化构造函数,不包括在内。
If you define a parameterized constructor, the default parameterless constructor is not included for you. Therefore you need to include it yourself.
从MSDN 10.10.4默认构造函数:
实例构造函数声明,会自动提供默认实例构造函数。
If a class contains no instance constructor declarations, a default instance constructor is automatically provided.
这篇关于C#相关的构造函数和属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!