如何像标准类型一样实例化 class 并赋值
How to instantiate a class and assign a value as with standard types
假设我有这样一个 class:
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;
我的意思是,这可能吗?
我是否必须在 class 中实现特定接口或其他任何东西才能做到这一点?
或者,如果我有这样的 class:
public class MyCustomList
{
private List<MyCustomObject>;
public int someRandomMethod() { /* ... */ }
}
用类似的东西实例化它:
MyCustomList myList = new List<MyCustomObject>() { 7, 25, 42 };
这可能没有任何意义,但我不认为我是第一个想到这样的人:D
感谢您的帮助!
塞尔吉奥
是的,有一个 way.You 可以从任何类型声明 implicit
conversions 到您的 type.For 示例:
public static implicit operator MyCustomObject(int x)
{
return new MyCustomObject { SomeProperty = x };
}
所以它不是特定于内置 types.But 的东西,这不是理想的方式 either.You 应该在必要且有意义的时候使用它。如果您想在初始化对象时编写更少的代码,请使用构造函数或对象初始化器。
假设我有这样一个 class:
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;
我的意思是,这可能吗?
我是否必须在 class 中实现特定接口或其他任何东西才能做到这一点?
或者,如果我有这样的 class:
public class MyCustomList
{
private List<MyCustomObject>;
public int someRandomMethod() { /* ... */ }
}
用类似的东西实例化它:
MyCustomList myList = new List<MyCustomObject>() { 7, 25, 42 };
这可能没有任何意义,但我不认为我是第一个想到这样的人:D
感谢您的帮助!
塞尔吉奥
是的,有一个 way.You 可以从任何类型声明 implicit
conversions 到您的 type.For 示例:
public static implicit operator MyCustomObject(int x)
{
return new MyCustomObject { SomeProperty = x };
}
所以它不是特定于内置 types.But 的东西,这不是理想的方式 either.You 应该在必要且有意义的时候使用它。如果您想在初始化对象时编写更少的代码,请使用构造函数或对象初始化器。