开发者

Setting A Member of Generic Object?

开发者 https://www.devze.com 2023-02-04 03:46 出处:网络
public class myclass { public int mymember { get; set; } } class MySetterClass<T> { // obj.mymember = o for myclass
public class myclass 
{
    public int mymember { get; set; }  
}

class MySetterClass<T>
{
    // obj.mymember = o for myclass
    public static void SetMember(string membername, obje开发者_运维知识库ct o, ref T obj)
    { 
    }
}

Can I do this with Reflection API ?

I have a generic class and I want to set a member of an instance.

Thanks in advance!


You can, but I'd warn against it. You are essentially doing an end-run around the type safety system, and there are a lot of pitfalls there.

If you must, the code is something like this, assuming that the member in question is a Property and not a Field:

typeof(T).GetProperty(membername).SetValue(obj, o);


Yes, you can. However, if you can do it without reflection, that would be best, since reflection is slow, cumbersome and harder to read and might indicate that your design is flawed.

I have to ask what your ultimate goal is with this code? Do you really want to just have a method that sets a member based on a string naming that member? Or do you want to be able to set a member on a generic type, but you know what it is at compile time? If it's the latter, then using generic constraints would something worth looking into. They allow the compiler to know the members on an object of a generic type at compile time.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号