c# - 通用函数

标签 c# generics nullreferenceexception

我正在尝试创建一个简单的通用函数:

    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/

相关文章:

c# - MVC html 助手如何使用表达式获取对象属性

c# - 用 C# 中的最后一个单词替换第一个单词

c# - IEqualityComparer 给出错误的结果

C# 泛型方法问题,TargetException,对象与目标类型不匹配

c# - 如何强制 Equals 返回 false 而不是 Null 引用异常?

asp.net - ASP.NET项目的单元测试出现问题(运行测试时出现NullReferenceException)

c# - 在 C#.Net 中将 ParentReference 从 Google Drive Apis v2 迁移到 v3

generics - 空接口(interface)与通用接口(interface)有何不同?

c# - 为什么是 ArgumentNullException?为什么不是 System.NullReferenceException?

c# - 我正在寻找指向 cdb/windbg + .net 文档的链接