This question already has answers here:
How to get a property value using reflection

(2个答案)


5年前关闭。




我正在尝试创建一个简单的泛型函数:
    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/

10-10 20:20