加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#:动态转换类型

发布时间:2020-12-15 18:28:48 所属栏目:百科 来源:网络整理
导读:我目前有这种类型的代码: private void FillObject(Object MainObject,Foo Arg1,Bar Arg2){ if (MainObject is SomeClassType1) { SomeClassType1 HelpObject = (SomeClassType1)MainObject; HelpObject.Property1 = Arg1; HelpObject.Property2 = Arg2; }
我目前有这种类型的代码:
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,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中是否可能?如果它比我现在的代码更混乱,那么我认为这样做没什么意义,但我很想知道.谢谢!

编辑:只是为了澄清,我完全理解实现一个接口是最合适的,也许是正确的解决方案.也就是说,我更感兴趣的是看看如何在不实现界面的情况下做到这一点.谢谢你的回复!

解决方法

看起来您关心的两种类型都实现了相同的两个属性.在这种情况下,您要做的是为这些属性定义一个接口:
public interface IMyInterface
{
   public Foo Property1 {get; set;}
   public Bar Property2 {get;set;}
}

然后,确保每个类告诉编译器他们实现了新接口.最后,使用一个泛型方法,该方法的类型参数受限于该interace:

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

请注意,即使使用额外的代码来声明界面,这些片段的结尾仍然比您在问题中发布的任何一个片段短,如果您关注的类型数量增加,则此代码更容易扩展.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读