我正在尝试创建一个简单的通用函数:
public T GetPost<T>(HttpListenerRequest request) where T : new()
{
Stream body = request.InputStream;
Encoding encoding = request.ContentEncoding;
StreamReader reader = new StreamReader(body, encoding);
string data = reader.ReadToEnd();
body.Close();
reader.Close();
// NullRefferenceException on this line:
typeof(T).GetField("Name").SetValue(null, "djasldj");
return //yet to come
}
奇怪的是 typeof(T)
的行返回此错误:
Object reference not set to an instance of an object.
What is a NullReferenceException, and how do I fix it?
另外我如何返回构造的T类?
这就是我调用该函数的方式:
string data = GetPost<User>(ctx.Request);
这是User
类:
public static string Name { get; set; }
public string Password { get; set; }
最佳答案
您的代码的问题在于您查找字段,但您的 T
具有自动属性。
因此您需要调用:
typeof(T).GetProperty("Name").SetValue(null, "djasldj");
例如,此代码(删除不必要的代码)有效:
class Foo {
public static string Name { get; set; }
public string Password { get; set; }
}
class Program
{
static void Main()
{
Console.WriteLine(Foo.Name);
GetPost<Foo>();
Console.WriteLine(Foo.Name);
}
public static void GetPost<T>() where T : new() {
typeof(T).GetProperty("Name").SetValue(null, "djasldj");
}
}
关于c# - 通用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28486099/