我必须根据构造函数的参数构建一个特殊的类行为。如果Foo绘画应该变成永久绿色,如果它是用绿色铅笔构建(绘制)的。 如果有铅笔在哪里使用,Foo应该是透明的...构造函数的优先顺序
现在,看下面的代码。是否有可能修改构造函数“查看”传入参数对象的实际类型的“输出”? (其实他们都是 “对象” S):
class Program
{
static void Main(string[] args)
{
object[] objs = { new IndexOutOfRangeException(), MyEnum.Beta, 45, new AssemblyName(), new { Name = "a" } };
for (int i = 0; i < objs.Length; i++)
{
Console.WriteLine("{0} => {1} ", i, objs[i]);
}
Console.WriteLine("=========================== ");
for (int i = 0; i < objs.Length; i++)
{
Foo myFoo = new Foo(objs[i]);
Console.WriteLine("{0} => {1}", i, myFoo);
}
}
}
public class Foo
{
object value;
string typeName;
public Foo(object obj)
{
value = obj;
typeName = "object";
}
public Foo(MyEnum enm)
{
value = enm;
typeName = "MyEnum";
}
public Foo(int myInt)
{
value = myInt;
typeName = "int";
}
public Foo(Exception ex)
{
value = ex;
typeName = "exception";
}
public override string ToString()
{
return string.Format("FOO (object = '{0}'; type = '{1}')", value, typeName);
}
}
public enum MyEnum
{
Alpha,
Beta
}
输出
0 => System.IndexOutOfRangeException: Index was outside the bounds of the array.
1 => Beta
2 => 45
3 =>
4 => { Name = a }
===========================
0 => FOO (object = 'System.IndexOutOfRangeException: Index was outside the bound
s of the array.'; type = 'object')
1 => FOO (object = 'Beta'; type = 'object')
2 => FOO (object = '45'; type = 'object')
3 => FOO (object = ''; type = 'object')
4 => FOO (object = '{ Name = a }'; type = 'object')
编辑:
正如看到一些答案,我想强调的是,是不是正确的字符串显示在“类型”变量中,例如使用value.GetType()
,但是关于“输入”正确的构造函数是问题。
换句话说,为什么编译器没有检测到正确的类型并将其“重定向”到正确的构造函数?
编辑2:
正如应答者提到的,“办法”来构造器“内置”在编译的时候,而不是在运行时。说喜欢他的
将输出
MyEnum en = MyEnum.Beta;
Console.WriteLine("Enum example: obj:{0} Foo:{1}", en, new Foo(en));
“好”输出代码:显然,像提出
Enum example: obj:Beta Foo:FOO (object = 'Beta'; type = 'MyEnum')
所以...任何方式“绕过”这种行为,但在构造函数中运行时的检测,里德科普塞...?!
编译器无法检测到类型,因为直到运行时才知道类型。因此它不能确定正确的cctor。 –
@David Neale:谢谢。我需要一个解决方法来“绕过”。 ) – serhio
使用反射('GetType()')获取类型名称的建议有什么问题?当你到达运行时,那是你可以做到这一点的唯一方法。否则 - 为什么你循环这些对象?有必要吗? –