我必須根據構造函數的參數構建一個特殊的類行爲。如果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()')獲取類型名稱的建議有什麼問題?當你到達運行時,那是你可以做到這一點的唯一方法。否則 - 爲什麼你循環這些對象?有必要嗎? –