有4个对象
public object ObjectGet = { get; set; }
public Object1TType Object1 = new Object1TType();
public Object2TType Object2 = new Object2TType();
public object Object3Set = new();
...
if ... => ObjectGet = new Object1TType(...)
else => ObjectGet = new Object2TType(...)
我知道代码本身可以有一个 Object3Set :
if (ObjectGet is Object1TType)
{
Object3Set = ObjectGet as Object1TType;
}
else if (ObjectGet is Object2TType)
{
Object3Set = ObjectGet as Object2TType;
}
但是如何根据全局对象的类型将对象 Object3Set的类型更改为Object1TType或Object2TType,以便我可以访问Object3Set.Field(假设我知道在这个地方它是 100% Object1TType )而无需在本地创建一个 Object3Set?
工作代码示例: 1.cs
namespace ObjectType
{
public class Object1TType : ICloneable
{
public ulong Field { get; set; }
public Object1TType()
{
}
public Object1TType( ulong Field)
{
this.Field = Field;
}
public object Clone()
{
return new Object1TType(Field);
}
}
public class Object2TType : ICloneable
{
public ulong Field { get; set; }
public Object2TType()
{
}
public Object2TType(ulong Field)
{
this.Field = Field;
}
public object Clone()
{
return new Object2TType(Field);
}
}
public class Class1
{
public static object ObjectGet = new Object1TType();
public static void Do()
{
ulong test = 123;
ObjectGet = new Object2TType(test);
}
}
}
2.cs
namespace Code
{
public class Main
{
public object ObjectGet = ObjectType.Class1.ObjectGet;
public object Object3Set = new();
public void Do()
{
ObjectType.Class1.Do();
if (ObjectGet is ObjectType.Object1TType)
{
Object3Set = ObjectGet as ObjectType.Object1TType;
}
else if (ObjectGet is ObjectType.Object2TType)
{
Object3Set = ObjectGet as ObjectType.Object2TType;
}
Console.WriteLine(Object3Set.Field);
}
}
}
在这里我无法访问ObjectGet.Field和Object3Set.Field,为此我认为我需要对Object3Set做一些事情并使用它