Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot using GetValues and SetValues in project C#

Tags:

c#

I want to convert DataRow To Object. I write 1 class to do this. Error like this:

No overload for method 'SetValue' takes 2 arguments

No overload for method 'GetValue' takes 1 arguments

But I can't using GetValues() and SetValues(). When converting project to 4.5. It's work. My project is set platform target is 3.5 (Obligatory - because I connect with the device must using .NET 3.5).

How to fix this?

Here my code:

    public DataRowToObject(DataRow row)
    {
        List<PropertyInfo> listProperty = this.GetProperties();
        foreach (PropertyInfo prop in listProperty)
        {
            if (!row.Table.Columns.Contains(prop.Name) ||
                row[prop.Name] == null ||
                row[prop.Name] == DBNull.Value)
            {
                prop.SetValue(this, null);
                continue;
            }

            try
            {
                object value = Convert.ChangeType(row[prop.Name], prop.PropertyType);
                prop.SetValue(this, value);
            }
            catch
            {
                prop.SetValue(this, null);
            }
        }
    }
    public virtual Hashtable GetParameters()
    {
        Type type = this.GetType();
        List<PropertyInfo> listProperty = new List<PropertyInfo>(type.GetProperties());

        Hashtable result = new Hashtable();
        foreach (PropertyInfo prop in listProperty)
        {
            result.Add(prop.Name, prop.GetValue(this));
        }

        return result;
    }

1 Answers

There is an overload for PropertyInfo.SetValue and PropertyInfo.GetValue without the indexer added in .NET 4.5.

But it's simply a matter of passing null to the indexer parameter on previous versions (using this and this overloads).

So:

prop.SetValue(this, value, null);

And

prop.GetValue(this, null);

This should work on .NET .3.5 (up to recent versions)... actually for NET 2.0 and up :-)

like image 77
Jcl Avatar answered Nov 23 '25 19:11

Jcl