简体   繁体   English

将变量类对象传递给类

[英]Passing a variable class object through to a class

I'm trying to work out if the following is possible, I've done lots of googling and I'm a bit confused. 我正在尝试解决以下问题,我已经做了很多谷歌搜索,但我有点困惑。 I'm pretty sure I can work out the class reflection on the object class and updating the database isn't a problem once I have the loop, but I can't work out if this is possible at all. 我很确定我可以解决对象类上的类反射问题,一旦有了循环,更新数据库就不成问题,但是如果有可能,我将无法解决。

If I was doing this with a fixed class object it'd be easy I'd just do: 如果我使用固定的类对象执行此操作,那么我会很容易做到:

public void updateDB(obj_Users myObject)

But as I have a lot of class objects that will take a long time, so trying to make it more dynamic. 但是由于我有很多类对象需要很长时间,因此请尝试使其更具动态性。

Here is a sample of a class I want to pass through (but could be anything following the same format): 这是我要传递的类的示例(但可以是遵循相同格式的任何内容):

public class obj_Users
{
    public Int32 UserID { get; set; }
    public String UserName { get; set; }
    public String FirstName { get; set; }
    public String Surname { get; set; }
    public String Email { get; set; }
    public Int32 UserRole { get; set; }
    public Int32 UserCompanyID { get; set; }
    public String UserPassword { get; set; }
    public Boolean IsAdmin { get; set; }
    public String SessionKey { get; set; }
}

Here is some pseudocode of what I'm trying to achieve to explain: 这是我要尝试解释的一些伪代码:

public void updateDB(AnyClassObject obj_Users)
{
    // Loop through obj_Users and grab the properties

    // DB update call
}

Try this to loop to get the properties 尝试循环以获取属性

foreach(var prop in obj_Users.GetType().GetProperties()) {
    //use your props
}

This: 这个:

public void updateDB(object paramobj)
{
    foreach(var prop in paramobj.GetType().GetProperties())
    {
           //grab
    }
    // update
 }

You just need your parameter to be of type object to pass an instance of any class or struct. 您只需要将参数的类型设置为object即可传递任何类或结构的实例。

public void updateDB(object whatever)
{
    foreach(var prop in whatever.GetType().GetProperties())
    {
       ... //do stuff
    }
} 

If you're stuck with the problem of having to deal with different classes, a generic method should fit your needs: 如果您不得不处理不同的类,那么通用方法应该可以满足您的需求:

public void UpdateDB<T>(T obj)
{
    var properties = typeof(T).GetProperties();

    foreach (var prop in properties)
    {
        // Here you loop through the properties.
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM