Bla*_*ade 12 .net c# clr constructor
前一阵子我问起了实例化一个HttpContext对象的问题.现在我已经学会了我不知道的东西,让我困惑的是你不能说HttpContext ctx = new HttpContext(); 因为该对象没有构造函数.
但是并不是每个类都需要构造函数?在C#中,如果您不提供,则编译器会自动为您提供默认的cstr.
另外,如果我有一个字符串(例如:"Hello There!")并且我说Convert.ToBoolean("Hello")或任何字符串,这是如何工作的?幕后发生了什么?我想像CLR Via C#这样的书在这种情况下会很方便.
我错过了什么?
HttpContext有一个带有两个重载的公共构造函数,但它不是默认值(没有参数).
例如,您需要传入SimpleWorkerRequest实例以便实例化HttpContext实例并将其分配给HttpContext.Current:
//Initialize this stuff with some crap
string appVirtualDir = "/";
string appPhysicalDir = @"C:\Documents and Settings\";
string page = @"localhost";
string query = string.Empty;
TextWriter output = null;
//Create a SimpleWorkerRequest object passing down the crap
SimpleWorkerRequest workerRequest = new SimpleWorkerRequest(appVirtualDir, appPhysicalDir, page, query, output);
//Create your fake HttpContext instance
HttpContext.Current = new HttpContext(workerRequest);
Run Code Online (Sandbox Code Playgroud)
请参阅此链接了解详情.
无论如何,一些类没有公共构造函数 - 例如,考虑单例类,构造函数是私有的(并且可以调用静态getInstance方法来获取当前实例,如果它为null则可以创建它).
干杯
| 归档时间: |
|
| 查看次数: |
9867 次 |
| 最近记录: |