本文介绍了c# 不能将类型 '' 隐式转换为 ''的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 C# 新手;请告诉我什么是坏的;

I'am new in C#;Please tell me what is bad;

我对这条消息有一个错误:

I have an error with this MESSAGE:

无法将类型Factory.ContactSite"隐式转换为Factory.Site""

我的代码:

class SiteFactory {

    public enum SiteType {
        Contact, Gallery, Info, News
    }

    public static Site makeSite(SiteType type) {

        switch (type) {

            case SiteType.Contact:
                {
                    return new ContactSite();   //create new object
                }
            case SiteType.Info:
                {
                    return new InfoSite();     //create new object
                }
            default:
                return null;
        }
    }
}

//-------------------------------------------------------------

//-----------------------------------------------------------------

class Site {

    public bool generate(String patch) {

        System.IO.FileStream f = new FileStream(patch, FileMode.Create);
        return true;
    }
}

//--------------------------------------------------------主要:

//------------------------------------------------------------main:

SiteFactory.makeSite(SiteFactory.SiteType.Contact).generate("file.txt");

class ContactSite 当前为空

class ContactSite is currently empty

推荐答案

我猜你需要做的是从 Site 派生类 InfoSiteContactSite 像这样:

I guess what you need to do is derive the classes InfoSite and ContactSite from Site like this:

public class ContactSite : Site
{

}

public class InfoSite : Site
{

}

当您调用 makeSite 以获取实例时,您必须将其转换为正确的 type,如下所示:

when you call makeSite to get an Instance you would have to cast it into the right type like this:

InfoSite infSite = SiteFactory.makeSite(SiteFactory.SiteType.Contact) as InfoSite;

这篇关于c# 不能将类型 '' 隐式转换为 ''的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-30 06:49