如何创建和访问一个匿名类的新实例在C#中的参数传递? [英] How do I create and access a new instance of an Anonymous Class passed as a parameter in C#?

查看:193
本文介绍了如何创建和访问一个匿名类的新实例在C#中的参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个函数,它接受一个SQL命令并产生,然后可以用于填充类实例的列表输出。该代码的伟大工程。我已经不包含异常处理在这里仅作参考稍微简化版本 - 如果你想直接跳到问题跳过此代码。如果您有任何建议在这里,虽然,我所有的耳朵。

I have created a function that takes a SQL command and produces output that can then be used to fill a List of class instances. The code works great. I've included a slightly simplified version without exception handling here just for reference - skip this code if you want to jump right the problem. If you have suggestions here, though, I'm all ears.

    public List<T> ReturnList<T>() where T : new()
    {
        List<T> fdList = new List<T>();
        myCommand.CommandText = QueryString;
        SqlDataReader nwReader = myCommand.ExecuteReader();
        Type objectType = typeof (T);
        FieldInfo[] typeFields = objectType.GetFields();
        while (nwReader.Read())
        {
            T obj = new T();
            foreach (FieldInfo info in typeFields)
            {
                for (int i = 0; i < nwReader.FieldCount; i++)
                {
                    if (info.Name == nwReader.GetName(i))
                    {
                        info.SetValue(obj, nwReader[i]);
                        break;
                    }
                }
            }
            fdList.Add(obj);
        }
        nwReader.Close();
        return fdList;
    }

正如我所说,这工作就好了。不过,我希望能够调用的类似功能具有的匿名类的原因是显而易见的。

As I say, this works just fine. However, I'd like to be able to call a similar function with an anonymous class for obvious reasons.

问题1:出现我要建设一个匿名类的实例在我打到我这个函数的匿名版本 - 这是正确的?一个例子调用:

Question #1: it appears that I must construct an anonymous class instance in my call to my anonymous version of this function - is this right? An example call is:

.ReturnList(new { ClientID = 1, FirstName = "", LastName = "", Birthdate = DateTime.Today });



问题2:我ReturnList功能的匿名版本低于。谁能告诉我为什么呼吁info.SetValue干脆什么都不做?它不会返回一个错误或什么,但它也不改变目标字段的值

Question #2: the anonymous version of my ReturnList function is below. Can anyone tell me why the call to info.SetValue simply does nothing? It doesn't return an error or anything but neither does it change the value of the target field.

    public List<T> ReturnList<T>(T sample) 
    {
        List<T> fdList = new List<T>();
        myCommand.CommandText = QueryString;
        SqlDataReader nwReader = myCommand.ExecuteReader();
        // Cannot use FieldInfo[] on the type - it finds no fields.
        var properties = TypeDescriptor.GetProperties(sample); 
        while (nwReader.Read())
        {
            // No way to create a constructor so this call creates the object without calling a ctor. Could this be a source of the problem?
            T obj = (T)FormatterServices.GetUninitializedObject(typeof(T)); 
            foreach (PropertyDescriptor info in properties)  
            {
                for (int i = 0; i < nwReader.FieldCount; i++)
                {
                    if (info.Name == nwReader.GetName(i))
                    {
                        // This loop runs fine but there is no change to obj!!
                        info.SetValue(obj, nwReader[i]);
                        break;
                    }
                }
            }
            fdList.Add(obj);
        }
        nwReader.Close();
        return fdList;
    }



任何想法?

Any ideas?

注意:当我尝试,因为我在上面的功能没有使用字段信息阵,阵typeFields有零个元素(即使对象类型显示的字段名称 - 怪)。因此,我用TypeDescriptor.GetProperties而不是

Note: when I tried to use the FieldInfo array as I did in the function above, the typeFields array had zero elements (even though the objectType shows the field names - strange). Thus, I use TypeDescriptor.GetProperties instead.

在使用反射或匿名类的任何其他提示和指导是适当这里 - 我是比较新的这个特定的角落。的C#语言

Any other tips and guidance on the use of reflection or anonymous classes are appropriate here - I'm relatively new to this specific nook of the C# language.

更新:我要感谢杰森为重点,以解决这一点。下面是修改后的代码将创建匿名类实例的列表,从查询填充每个实例的领域。

UPDATE: I have to thank Jason for the key to solving this. Below is the revised code that will create a list of anonymous class instances, filling the fields of each instance from a query.

   public List<T> ReturnList<T>(T sample)
   {
       List<T> fdList = new List<T>();
       myCommand.CommandText = QueryString;
       SqlDataReader nwReader = myCommand.ExecuteReader();
       var properties = TypeDescriptor.GetProperties(sample);
       while (nwReader.Read())
       {
           int objIdx = 0;
           object[] objArray = new object[properties.Count];
           foreach (PropertyDescriptor info in properties) 
               objArray[objIdx++] = nwReader[info.Name];
           fdList.Add((T)Activator.CreateInstance(sample.GetType(), objArray));
       }
       nwReader.Close();
       return fdList;
   }

请注意,该查询已经建成,并在以前调用此初始化参数对象的方法。原代码有一个内/外循环组合,使得用户可以在他们的匿名类字段没有一个字段匹配。然而,为了简化设计,我决定不准许这一点,并而是通过推荐杰森的数据库字段的访问。此外,由于戴夫马克尔也帮助我了解更多关于使用Activator.CreateObject()与GenUninitializedObject的权衡。

Note that the query has been constructed and the parameters initialized in previous calls to this object's methods. The original code had an inner/outer loop combination so that the user could have fields in their anonymous class that didn't match a field. However, in order to simplify the design, I've decided not to permit this and have instead adopted the db field access recommended by Jason. Also, thanks to Dave Markle as well for helping me understand more about the tradeoffs in using Activator.CreateObject() versus GenUninitializedObject.

推荐答案

匿名类型封装一组的只读的属性。这就解释了

Anonymous types encapsulate a set of read-only properties. This explains


  1. 为什么 Type.GetFields 调用时返回一个空数组在你的匿名类型:匿名类型不具有公共字段

  1. Why Type.GetFields returns an empty array when called on your anonymous type: anonymous types do not have public fields.

这是匿名类型的公共属性只能读,不能有其价值被设定。到 PropertyInfo.SetValue 的电话。如果你在一个匿名类型调用 PropertyInfo.GetSetMethod 上的属性,您将收到回

The public properties on an anonymous type are read-only and can not have their value set by a call to PropertyInfo.SetValue. If you call PropertyInfo.GetSetMethod on a property in an anonymous type, you will receive back null.

在事实上,如果你改变

var properties = TypeDescriptor.GetProperties(sample);
while (nwReader.Read()) {
    // No way to create a constructor so this call creates the object without calling a ctor. Could this be a source of the problem?
    T obj = (T)FormatterServices.GetUninitializedObject(typeof(T)); 
    foreach (PropertyDescriptor info in properties) {
        for (int i = 0; i < nwReader.FieldCount; i++) {
            if (info.Name == nwReader.GetName(i)) {
                // This loop runs fine but there is no change to obj!!
                info.SetValue(obj, nwReader[i]);
                break;
            }
        }
    }
    fdList.Add(obj);
}



to

PropertyInfo[] properties = sample.GetType().GetProperties();
while (nwReader.Read()) {
    // No way to create a constructor so this call creates the object without calling a ctor. Could this be a source of the problem?
    T obj = (T)FormatterServices.GetUninitializedObject(typeof(T));
    foreach (PropertyInfo info in properties) {
        for (int i = 0; i < nwReader.FieldCount; i++) {
            if (info.Name == nwReader.GetName(i)) {
                // This loop will throw an exception as PropertyInfo.GetSetMethod fails
                info.SetValue(obj, nwReader[i], null);
                break;
            }
        }
    }
    fdList.Add(obj);
}

您会收到一个异常,通知您属性设置方法不能发现

you will receive an exception informing you that the property set method can not be found.

现在,解决你的问题,你可以做的是使用 Activator.CreateInstance 。我很抱歉,我懒得给你打出来的代码,但下面将展示如何使用它。

Now, to solve your problem, what you can do is use Activator.CreateInstance. I'm sorry that I'm too lazy to type out the code for you, but the following will demonstrate how to use it.

var car = new { Make = "Honda", Model = "Civic", Year = 2008 };
var anothercar = Activator.CreateInstance(car.GetType(), new object[] { "Ford", "Focus", 2005 });



因此​​,只要通过一个循环运行,为你做,以填补对象数组,你需要传递给 Activator.CreateInstance ,然后调用 Activator.CreateInstance 当循环完成。两个匿名类型相同属性顺序是这里重要的当且仅当它们有相同数量在同一顺序的相同类型和名称相同的属性。

So just run through a loop, as you've done, to fill up the object array that you need to pass to Activator.CreateInstance and then call Activator.CreateInstance when the loop is done. Property order is important here as two anonymous types are the same if and only if they have the same number of properties with the same type and same name in the same order.

如需更多信息,请参见匿名类型的 MSDN页面

For more, see the MSDN page on anonymous types.

最后,这是一个真正的放在一边,没有密切关系你的问题,但下面的代码

Lastly, and this is really an aside and not germane to your question, but the following code

foreach (PropertyDescriptor info in properties) {
    for (int i = 0; i < nwReader.FieldCount; i++) {
        if (info.Name == nwReader.GetName(i)) {
            // This loop runs fine but there is no change to obj!!
            info.SetValue(obj, nwReader[i]);
            break;
        }
    }
}



可以通过

could be simplified by

foreach (PropertyDescriptor info in properties) {
            info.SetValue(obj, nwReader[info.Name]);
}

这篇关于如何创建和访问一个匿名类的新实例在C#中的参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆