ITPub博客

首页 > > > 静态方法中实例化的对象问题

静态方法中实例化的对象问题

作者:fondtiger 时间:2019-09-17 15:47:05 0 删除 编辑
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
User user =null;
user.ToHelloWorld ();
if (user == null)
{
Console.Write("world");
Console.Read();
}
else
{
Console.Write(user.UserName);
Console.Read();
}

        }
        catch
        {
            Console.Write("hello world");
            Console.Read();
        }
    }
}

public class User
{
    public string UserId { get; set; }
    public string UserName { get; set; }
}

public static class UserExtention
{
    public static void ToHelloWorld(this User user)
    {
        if (user == null)
        {
            user = new User() { UserName = "hello" };
        }
    }
}
}

这段代码的输出结果为WORLD。调试发现在执行完 user.ToHelloWorld ();后User还是为NULL。请问大神们这是为什么?

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2508/viewspace-3163328/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-09-29

  • 博文量
    122
  • 访问量
    13449