泛型函数

Generic function

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

    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) return 行出现这个错误:

Object reference not set to an instance of an object.

What is a NullReferenceException, and how do I fix it?

另外,我如何return构造T class?

我是这样调用函数的:

 string data = GetPost<User>(ctx.Request);

这是 User class:

public static string Name { get; set; }
public string Password { get; set; }

恐怕您正在尝试设置 T 的 属性。但是 T 只是您传递给泛型方法的一种类型。你已经用 new() 约束了它,据我所知 T 类型应该提供无参数构造函数。

假设你称它为 GetPost<User>(request);

它应该 return 用户设置了一些属性。看看那个例子(用户 class 就像你写的那样)...

这是一个 class 通用方法:

namespace ConsoleApplication1
{
    class Class1
    {
        public T GetPost<T>(string s) where T : new()
        {
            if (typeof(T)== typeof(User))
            {
                var result = new User();
                result.Password = "some";
                return (T)(object)result;
            }
            else
            {
                throw new ArgumentException();
            }
        }
    }
}

这是用法

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var c = new Class1();
            var obj = c.GetPost<User>("dsjkd");
        }
    }
}

执行后变量"obj"是设置了密码字段的用户对象。

编辑:

我刚看过 CommuSoft post。我认为这是更好的解决方案,但我不会删除我的答案,也许有人会觉得它有用。

您的代码的问题是您要查找一个字段,但是您的 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");
    }

}