如何实例化类并使用标准类型分配值

时间:2015-01-19 21:09:36

标签: c# .net wpf visual-studio-2013 windows-runtime

我们说我有一个这样的课程:

public class MyCustomObject
{
    //For Type I mean int, String, or any other Type I might want to use
    private Type variable;

    public int someRandomMethod() { /* ... */ }
}

有没有办法用简单的声明和赋值来实例化它,比如

MyCustomObject test = 20; //If I had int as my variable type

就像:

String check1 = "Here I'm creating a new String";
Int32 myNumber = 42;

我的意思是,有可能吗?

我是否必须在课程中实现特定的界面或其他任何内容才能做到这一点?

或者,如果我有这样的课程:

public class MyCustomList
{
    private List<MyCustomObject>;

    public int someRandomMethod() { /* ... */ }
}

用以下内容实例化它:

MyCustomList myList = new List<MyCustomObject>() { 7, 25, 42 };

这可能没有任何意义,但我不认为我是第一个想到这样的人:D

感谢您的帮助!

塞尔吉奥

1 个答案:

答案 0 :(得分:3)

是的,有一种方法。您可以从任何类型向您的类型声明implicit conversions。例如:

public static implicit operator MyCustomObject(int x)
{
    return new  MyCustomObject { SomeProperty  = x };
}

所以它不是内置类型的特定内容。但这也不是一种理想的方式。你应该在必要时使用它并且有意义。如果你想在初始化对象时使用构造函数或对象初始化器来编写更少的代码。

相关问题