gpt4 book ai didi

c# - 多态性和转换问题

转载 作者:太空宇宙 更新时间:2023-11-03 17:35:48 25 4
gpt4 key购买 nike

为了说明我的问题这里举个例子

namespace CheckAbstarct
{

class Program
{
static void Main(string[] args)
{
myAbstarctClass mac1 = ObjectFactory.ObjectCreator("aaa");
myAbstarctClass mac2 = ObjectFactory.ObjectCreator("bbb");
mac1.changeMyString();
mac2.changeMyString();
string myString = (string)mac2.returnMyObject();
DateTime myObject = (DateTime) mac1.returnMyObject();

object obj1 = mac1.returnMyObject();
object obj2 = mac2.returnMyObject();

myMethod(obj1); //---> This is not compiling
myMethod(obj2); //---> This is not compiling

myMethod(myString); //---> works fine
myMethod(myObject); //---> works fine

Console.ReadKey();
}
public static void myMethod(DateTime dt)
{
}
public static void myMethod(string st)
{
}
}
abstract class myAbstarctClass
{
protected string mMyString;
public myAbstarctClass()
{
mMyString = "myAbstarctClass ";
}
public abstract void changeMyString();
public abstract object returnMyObject();
}

class MyNewAbstractClass1 : myAbstarctClass
{
DateTime mObject;
public MyNewAbstractClass1(string myString)
{
mMyString = myString;
mObject = new DateTime().Date;
}
public override void changeMyString()
{
mMyString += " MyNewAbstractClass1";
Console.WriteLine(mMyString);
}
public override object returnMyObject()
{
return mObject;
}
}

class MyNewAbstractClass2 : myAbstarctClass
{
string mString;
public MyNewAbstractClass2(string myString)
{
mMyString = myString;
mString = mMyString;
}
public override void changeMyString()
{
mMyString += " MyNewAbstractClass2";
Console.WriteLine(mMyString);
}
public override object returnMyObject()
{
return mString;
}
}

static class ObjectFactory
{
public static myAbstarctClass ObjectCreator(string myString)
{
switch (myString)
{
case "aaa":
return new MyNewAbstractClass1(myString);
case "bbb":
return new MyNewAbstractClass2(myString);
default:
return null;
}
}
}
}

我的问题是,在 Main() 中,我不知道 returnMyObject() 方法返回什么类型,所以我无法将它发送到 MyMethod。有没有办法转换对象??

最佳答案

因为在您的 returnMyObject() 设计中,您回到了最常见的 object 引用,您必须在运行时找出:

if (obj1 is string)
myMethod((string)obj1); //--->cast it
else if (obj1 is DateTime)
myMethod((DateTime) obj1);

关于c# - 多态性和转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3414553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com