How can I use a local variable in a method from another method?

こ雲淡風輕ζ 提交于 2021-02-05 10:50:06

问题


private void UserYoutubeService()
{
    var youtubeService = new YouTubeService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
    });
}

And I want to use the variable youtubeService in this method:

static List<string> videosList = new List<string>();

public async void RetrieveUploadsList()
{
    UserCredentials();
    UserYoutubeService();

    var channelsListRequest = youtubeService.Channels.List("contentDetails");
}

I'm using the method UserYoutubeService in other places in my code but now I need to use the local variable youtubeService properties in the method RetrieveUploadsList. How can I pass the variable youtubeService out of the UserYoutubeService?


回答1:


The simplest way would be to return the value you want from UserYoutubeService, as in:

private YouTubeService UserYoutubeService() // <-- Note return type
{
    return new YouTubeService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
    });
}

Which you would use like this:

public async void RetrieveUploadsList()
{
    UserCredentials();
    var youtubeService = UserYoutubeService(); // <--- Change is here

    var channelsListRequest = youtubeService.Channels.List("contentDetails");
    ...


来源:https://stackoverflow.com/questions/32550630/how-can-i-use-a-local-variable-in-a-method-from-another-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!