Type-ing:如何传递类型?
我的数据库中有几个表,它们都包含不同的 DataRow 继承类型。
另外我有一个类应该处理我的 DataGrid 中的一些事情 (我的数据库表已连接到 DataGrid)。
为此,此 DataGrid 处理程序中的方法之一必须将行强制转换为 DataRow 的确切继承类型。
像这样的东西: (TempDataRow 作为 DataRowTypeThatInheritsFromRegularDataRow)。SpecialParameter = 某事;
为此,我必须将继承的 DataRow 类型传递给该方法,以便它知道如何进行转换。
该方法通常如下所示:
public void DoSomething(DataRowType Type) { (TempDataRow 作为类型).SpecialParameter = some; 如何
传递类型? 常规“Type”类型无法编译。 如果我只传递“DataRow”,它将不知道如何进行转换。
I have a few tables in my database and they all contain a different inherited type of a DataRow.
In addition I have a class that is supposed to handle some things in my DataGrid
(My database Tables are connected to DataGrids).
In order to do that, one of the methods in this DataGrid handler has to cast the rows to the exact inherited type of a DataRow.
something like this:
(TempDataRow as DataRowTypeThatInheritsFromRegularDataRow).SpecialParameter = something;
In order to do that, I have to pass the method the inherited DataRow type, so it will know how to do the casting.
The method will generally look like this:
public void DoSomething(DataRowType Type)
{
(TempDataRow as Type).SpecialParameter = something;
}
How to pass the type?
Regular 'Type' type does not compile.
and if I pass just 'DataRow' it won't know how to do the casting.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用 C# 4.0,那么您是否考虑过使用“动态”类型?
此示例应根据 getDataRow() 实际返回的内容在运行时选择要调用的函数。
有关 dynaminc 的进一步阅读,请参阅 msdn
If you are using C# 4.0, then have you considered the use of the 'dynamic' type?
This example should choose at run-time which function to call, based upon what getDataRow() actually returns.
For further reading of dynaminc see msdn
有多种方法可以做到这一点。
首先,您可以找到所有类型共享的公共基类或接口,然后让 DoSomething() 获取该基类或接口,或者如果您想完全动态,则可以使用反射。很难告诉你如何做到这一点,因为你没有给出任何具体的例子:(
尽管如果你使用 C# 4.0,正如 TK 指出的那样,你可以只使用动态类型并完成它!)
There are a number of ways you could do this.
First, you could find a common base class or interface that all types share, and then have DoSomething() take that base class or interface, or if you want to be totally dynamic, you could use reflection. It's hard to tell you how to do it, because you haven't given any concrete example:
(though if you were using C# 4.0, as TK points out, you could just use the dynamic type and be done with it!)
你可以使用:
You could use: