English 中文(简体)
使用动态接口中未定义的通用型出入财产
原标题:Access property of generic type not defined in interface using dynamic

I m having to modify a lot of code to set a SqlCe database connection for a bunch of table adapters. I would like to avoid the duplication involved and minimise the chance I ve missed updating a table adapter by creating a generic method to wrap the creation of each table adapter. Unfortunately the table adapters aren t derived from a single base class and each has it s own Connection property. By assigning the new table adapter to dynamic I can get it to compile. Is this a good approach and are there any traps I should be aware of when using dynamic?

protected void TableAdapter<T>(Action<T> action) where T : IDisposable, new()
{
    using (var connection = new SqlCeConnection(ConnectionString))
    using (dynamic tableAdapter = new T())
    {
        tableAdapter.Connection = connection;
        action(tableAdapter);
    }
}
最佳回答

Nah,无陷阱。 我认为,你正在就改进的可读性交换一份汇编文件。 如果有人使用该代码是错误的,那么时间错误就会很明显:<代码> 链接 成员t 。

在个人方面,我还要补充行动论点,因为必须积极援引行动。 但是,我认为,由于绩效收益可能微不足道,因此可以选择一种选择,而我的人的风格是将动态使用的范围限制在目的性。

protected void TableAdapter<T>(Action<T> action) where T : IDisposable, new()
{
    using (var connection = new SqlCeConnection(ConnectionString))
    using (dynamic tableAdapter = new T())
    {
        tableAdapter.Connection = connection;
        action((T)tableAdapter);
    }
}
问题回答

这种做法虽然可行,但对于C#来说,它是一种比喻的氧化物。 这里是一种替代选择,它牺牲了南盟的一小部分,用于编纂时的安全:

protected void TableAdapter<T>(Action<T, SqlCeConnection> action) where T : IDisposable, new()
{
    using (var connection = new SqlCeConnection(ConnectionString))
    using (var tableAdapter = new T())
    {
        action(tableAdapter, connection);
    }
}

既然你的行动需要除了它所做的任何事情外,还要建立这一联系,但汇编者要核实这些联系,而且你并没有对有活力的总结者处以实绩的惩罚。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签