gpt4 book ai didi

C#:动态转换类型

转载 作者:太空狗 更新时间:2023-10-29 20:43:22 25 4
gpt4 key购买 nike

我目前有这种类型的代码:

private void FillObject(Object MainObject, Foo Arg1, Bar Arg2)
{
if (MainObject is SomeClassType1)
{
SomeClassType1 HelpObject = (SomeClassType1)MainObject;
HelpObject.Property1 = Arg1;
HelpObject.Property2 = Arg2;
}
else if (MainObject is SomeClassType2)
{
SomeClassType2 HelpObject = (SomeClassType2)MainObject;
HelpObject.Property1 = Arg1;
HelpObject.Property2 = Arg2;
}
}

假设 SomeClassType1 和 SomeClassType2 具有我要分配的同一组属性(尽管它们在其他方面可能不同),是否可以动态地将 MainObject 转换为适当的类型然后分配值,而无需重复代码?这是我最终希望看到的:

private void FillObject(Object MainObject, Foo Arg1, Bar Arg2)
{
Type DynamicType = null;

if (MainObject is SomeClassType1)
{
DynamicType = typeof(SomeClassType1);
}
else if (MainObject is SomeClassType2)
{
DynamicType = typeof(SomeClassType2);
}

DynamicType HelpObject = (DynamicType)MainObject;
HelpObject.Property1 = Arg1;
HelpObject.Property2 = Arg2;
}

显然 C# 提示找不到 DynamicType:

The type or namespace name 'DynamicType' could not be found (are you missing a using directive or an assembly reference?)

在 C# 2.0 中可以实现这样的功能吗?如果它比我当前的代码更困惑,那么我认为这样做没有意义,但我很想知道。谢谢!

编辑:澄清一下,我完全理解实现接口(interface)是最合适且可能是正确的解决方案。也就是说,我更感兴趣的是如何在不实现接口(interface)的情况下做到这一点。感谢您的精彩回复!

最佳答案

看起来您关心的两种类型都实现了相同的两个属性。在这种情况下,您要做的是为这些属性定义一个接口(interface):

public interface IMyInterface
{
public Foo Property1 {get; set;}
public Bar Property2 {get;set;}
}

然后,确保您的每个类都告诉编译器它们实现了新接口(interface)。最后,使用带有受限于该接口(interface)的类型参数的泛型方法:

private void FillObject<T>(T MainObject, Foo Arg1, Bar Arg2) 
where T : IMyInterface
{
MainObject.Property1 = Arg1;
MainObject.Property2 = Arg2;
}

请注意,即使使用额外的代码来声明接口(interface),这些片段最终仍然比您在问题中发布的任何一个片段都短,并且如果您关心的类型数量增加,则此代码更容易扩展.

关于C#:动态转换类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/566510/

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