【发布时间】:2013-10-02 09:34:18
【问题描述】:
我已经定义了这样一个函数:
public static void WriteResponse(ref HttpContext ctx, object sender, Type typeName)
{
var model = sender as typeName; // it's an error-line, becase of `as typeName`
var jsonObject = new JavaScriptSerializer().Serialize(model);
ctx.Response.AddHeader("Access-Control-Allow-Origin", "*");
ctx.Response.ContentType = "Content-type: application/json";
ctx.Response.ContentEncoding = Encoding.UTF8;
ctx.Response.Write(jsonObject);
}
如您所见,它甚至无法编译,因为以下行:
var model = sender as typeName;
我从那个调用这个函数:
internal void GetShortInfo(ref HttpContext ctx, ref Shapefile shapefile)
{
var model = new Models.SfShortInfo()
{
Count = shapefile.Count,
Type = shapefile.Type.ToString()
};
ShapefileService.WriteResponse(ref ctx, (object)model, model.GetType());
}
还有这样的电话:
ShapefileService.WriteResponse(ref ctx, (object)model, model.GetType());
我想从自己设计的 API Web 服务中添加任何功能。
我想,你有一个想法,我正在尝试什么TO DO。
我想定义一个函数,它可以通过将模型实例装箱到 System.Object 并为 JSON 响应拆箱来接受来自各种数量的其他函数的调用。
类似于 C++ 中的reinterpret_cast<> 函数。我认为,我可以使用 Generics 在 C# 中完成它,但我不太了解 C# 的那部分,所以我建议您提供帮助。
谢谢!
【问题讨论】:
-
我认为您拼错了“为什么?”在问题标题中
-
公平地说,这个标题对于 C++ 程序员来说有点奇怪(我们拥有该reinterpret-cast标签的权利)
-
@sehe 你为什么这么认为?
-
这完全不像我书中的
reinterpret_cast。更像dynamic_cast -
你为什么还要尝试提出论点?据我所知,
Serialize方法采用object...
标签: c# templates generics boxing reinterpret-cast