我在下面的c#代码的第3行中获得错误作为对象引用而不是设置实例oc对象

问题描述:

HttpRequest request = context.Request;

HttpResponse response = context.Response;

string fromdate1 = request [from]。ToString();

string fromdate = dateConvert1(fromdate1);

string todate1 = request [to]。ToString();

string todate = dateConvert1(todate1) ;

HttpRequest request = context.Request;
HttpResponse response = context.Response;
string fromdate1 = request["from"].ToString();
string fromdate = dateConvert1(fromdate1);
string todate1 = request["to"].ToString();
string todate = dateConvert1(todate1);

1。第一个解决方案的第一部分是OK,你试图使用 request 缓存中找不到的东西。



2.解决方案更简单,只需使用 null 进行测试,并从已经是字符串的缓存中获取值而不是使用 ToString()

1. The first part from the 1st solution is OK, you are trying to use something that is not found in the request cache.

2.The solution is more simple, just to test with null and to get value from the cache that is already a string and not to use ToString().
string fromdate1 = (request["from"] == null ? string.Empty : request["from"]); 



PS:请注意,在Web应用程序缓存中(例如 Session Application 等),数据通过使用装箱(作为对象)保存,比从缓存中获取内容时应使用拆箱而不是 ToString(),如下所示:


PS: Note that in the web application caches (like Session, Application, etc.), the data are saved by using boxing (as objects), than when you get something from cache you should use unboxing and not ToString(), like below:

string userName = (string)Session["UserName"];



有关装箱和拆箱的更多详细信息,请参阅MSDN: http://msdn.microsoft。 com / zh-CN / library / yz2be5wk.aspx [ ^ ]


此错误表示存在null。



This error saying that there is something "null".

string fromdate1 = request["from"].ToString();



如果你在这行中出错,有可能那个请求[from]是null。

所以如果请求[from]为null那么它就不可能写成......




if you are getting error in this line there is possibility that request["from"] is null.
so if request["from"] is null then its not possible to write like...

// if request["from"] is null then your code seems like...
null.ToString();
//This is not Allowed.





你最好在使用它之前检查它是否为空。



You better check if its null or not before you use this.

string fromdate1 = !string.IsNullOrEmpty(request["from"]) ? request["from"].ToString() : string.empty;





希望此帮助。



Hope this Help.