[英]Make instance of “object” to other class and call method
我想定義一個object
並將其實例化為其他類,但是我無法調用該方法,這是我的代碼:
class Test1
{
public bool True_1()
{return true;}
}
class Test2
{
public bool True_2()
{return true;}
}
class MainClass
{
static void Main()
{
object a;
bool flag = true; // or false
if (flag)
a = new Test1();
else
a = new Test2();
if (a is Test1)
a.True_1(); //error before compiling
else
a.True_2(); //error before compiling
}
}
}
我知道有一種創建接口I_Test
,並執行以下操作:
class Test1:I_Test
class Test2:I_Test
但是由於類Test2
是來自第三方的dll,所以我不能在其中添加:I_Test
,所以我想在這里實現我的代碼,有什么建議嗎? 謝謝!
如果您使用的是C#7,則可以使用新語法,該語法允許您測試並將測試結果放入一行中的變量中:
if (a is Test1 aTest)
aTest.True_1();
else if( a is Test2 aTest2)
aTest2.True_2();
如果您使用的是較舊的C#,則可以將as
運算符與null測試結合使用:
var aTest = a as Test1;
if (aTest != null)
aTest.True_1();
else
{
var aTest2 = a as Test2;
if (aTest2 != null)
{
aTest2.True_2();
}
}
您還可以使用測試和強制轉換解決方案,以最大程度地減少變量的數量,因此不建議這樣做,因為這可能會迫使運行時進行兩次測試(一次is
,一次強制轉換)。 請參閱此問題以獲取更詳細的答復
if(a is Test1)
((Test1)a).True_1();
您可以執行以下兩種解決方案來解決此問題:1.將a
轉換為所需的類,然后可以調用該方法:嘗試以下操作:
static void Main()
{
object a;
bool flag = true;
if (flag)
a = new Test1();
else
a = new Test2();
if (a is Test1)
{
((Test1)a).True_1(); //So, there will be no error anymore
}
else
{
((Test2)a).True_2();
}
}
使用dynamic
關鍵字而不是object
類型。 嘗試這個:
static void Main() { dynamic a; bool flag = true; if (flag) a = new Test1(); else a = new Test2(); if (a is Test1) a.True_1(); //So, there will be no error anymore else a.True_2(); }
你必須先投
if(a is Test1 aConverted)
aConverted.True_1();
或更舊的方式:
if(a is Test1)
((Test1)a).True_1();
假設您有一個包含類的第三方DLL ...
class ThirdPartyClass
{
public bool Foo { get { return true;} }
}
您想要創建自己的類,該類具有與第三方類相同的方法或屬性:
class MyClass
{
public bool Foo { get { return true;} }
}
如您所述,通常要做的是向第三方類添加接口,然后在您自己的類中實現該接口。 但正如您還指出的那樣,您不能這樣做。 而且,由於沒有通用的接口,您只能使用笨拙的if / then構造。
如果我正確了解您的情況,可以按照以下方式處理。 擴展第三方類以添加接口,如下所示:
interface IMyInterface
{
bool Foo { get; }
}
class MyThirdPartyClass : ThirdPartyClass, IMyInterface
{
}
由於Foo
是公共的,因此它將被繼承並可用,並滿足該接口。 現在您也可以創建自己的類:
class MyClass : IMyInterface
{
public bool Foo { get { return true; }}
}
您可以互換使用它們:
IMyInterface a = new MyThirdPartyClass();
IMyInterface b = new MyClass();
bool c = a.Foo;
bool d = b.Foo;
我就是那樣做的。
如果第三方類被密封,您可能會遇到問題。 如果是這種情況,則必須包裝它而不是繼承它:
class MyThirdPartyClassWrapper : IMyInterface
{
private readonly ThirdPartyClass _wrappedInstance = new ThirdPartyClass();
public bool Foo { get { return _wrappedInstance.Foo; } }
}
然后它仍然可以工作:
IMyInterface a = new MyThirdPartyClassWrapper();
IMyInterface b = new MyClass();
bool c = a.Foo;
bool d = b.Foo;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.