简体   繁体   English

使用匿名对象+动态是否不明智?

[英]Is it unwise to use anonymous object + dynamic?

I have a class where one of the property return a List<object> . 我有一个类,其中一个属性返回List<object> Inside that list I put a set of anonymous objects. 在该列表中,我放置了一组匿名对象。

Then later of, I have a loop using that property's item as dynamic variable. 然后,稍后,我将使用该属性的项目作为动态变量进行循环。
So my code looks like this: 所以我的代码看起来像这样:

private List<object> BookerTypes
{
    get
    {
        if (this.bookerTypes == null)
        {
            this.bookerTypes = new List<object>();

            var com = new SqlConnection(functions.ConnectionString).CreateCommand();
            com.CommandText = @"
SELECT
    BT.id
    , BT.name
FROM dbo.BookerTypes AS BT
ORDER BY BT.name ASC
";
            com.Connection.Open();
            try
            {
                using (var dr = com.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        this.bookerTypes.Add(new { id = dr.GetInt32(0), name = dr.GetString(1) });
                    }
                }
            }
            finally
            {
                com.Connection.Close();
            }
        }

        return this.bookerTypes;
    }
}

[...] [...]

    this.cblSBT.Items.Clear();
    foreach(dynamic bt in this.BookerTypes)
    {
        this.cblSBT.Items.Add(new ListItem()
        {
            Value = bt.id.ToString()
            , Text = bt.name
            , Selected = this.competition.SubscriptionTypes.Contains((int)bt.id)
        });
    }

Aside from the obvious lost of strongly typed type, is there any reason I should not do this? 除了明显的强类型丢失之外,还有什么理由我不应该这样做吗?

The primary reason not to do this is, as you said, you've lost your static typing. 如您所说,不这样做的主要原因是您丢失了静态类型。 There are also performance costs associated with it as well, but they're less important than the noticable problem this code has in terms of readability and maintainability. 也有与此相关的性能成本,但是就可读性和可维护性而言,它们不如此代码显着的问题重要。

If it turns out that you misspell or mistype a variable name you don't get compile time checking (and it's easier to do without code completion support). 如果事实证明您错误拼写或错误键入了变量名,则不会进行编译时检查(如果没有代码完成支持,这样做会更容易)。 You also don't have any effective means of knowing, at compile time, what variables might exist in the List<object> you're given. 在编译时,您也没有任何有效的方法来知道给定的List<object>可能存在哪些变量。 It becomes a non-trivial task to track down the source of that list to figure out what variables might be there to use. 跟踪列表的源以找出可能要使用的变量是一项艰巨的任务。

It is almost certainly worth the time and effort to create a new named type instead of using an anonymous type when you're in this situation. 在这种情况下,几乎肯定值得花费时间和精力来创建新的命名类型,而不是使用匿名类型。 The small up front cost of creating the new class is virtually always going to pay off. 创建新类的前期成本几乎总是可以得到回报的。

On top of the type-safety loss & other concerns which have already been pointed out, I feel using dynamic here is just plain wrong. 除了已经指出的类型安全损失和其他问题之外,我觉得在这里使用dynamic是完全错误的。

The general use-case for dynamic is for consuming data from external sources eg API/COM etc. basically scenarios where the type of information isn't already clearly defined. dynamic的一般用例是从外部资源(例如API / COM等)中消费数据。基本上,这些场景中的信息类型尚未明确定义。 In your scenario, you have control over what data you are asking for and you know what type of data to expect therefore I can't really justify why you would want to use it over the benefits gained from having a clearly defined, type-safe model. 在您的方案中,您可以控制所需的数据,知道所需的数据类型 ,因此我无法真正辩解为什么要使用数据,而不要通过明确定义的类型安全性而获得收益模型。

Is it unwise to use anonymous object + dynamic? 使用匿名对象+动态是否不明智?

In your scenario, I would argue yes. 在您的情况下,我认为是。

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

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