我有一个旧VB6应用程序,有一个功能RunReturningVAR这是一个分贝的呼叫时可能会返回int
,string
,double
.....但不是RecordSet
.它的构建非常通用,因此可以通过多个其他函数调用它,因此我们没有多个DB调用位置.我目前拥有的是附件.
Public Function RunReturningVar(ByVal vstrSql As String, _
Optional ByVal connval As Boolean = False, _
Optional ByVal copyID As Double = 0, _
Optional ByVal corpVal As Boolean = False, _
Optional ByVal vintConnectionTimeout As Integer = 30) As Variant
Run Code Online (Sandbox Code Playgroud)
VB6 Variant
(不敢相信我发现了链接!)翻译c#dynamic
.
public dynamic RunReturningVar(
string vstrSql,
bool connval = false,
double copyID = 0,
bool corpVal = false,
int vintConnectionTimeout = 30)
{
// do your stuff here
}
Run Code Online (Sandbox Code Playgroud)
它几乎转换为object
,但是Variant
是特定于后期绑定的数据类型,它可以保存引用类型和值类型 - 不像c#object
只能通过装箱来保存值类型.
请注意,使用dynamic
意味着您绕过所有编译时类型检查,这可能导致运行时错误,这通常是您不希望从ac#程序.
也许你可以用泛型做得更好,但这需要你从调用方法中指定返回类型:
public T RunReturningVar<T>(
string vstrSql,
bool connval = false,
double copyID = 0,
bool corpVal = false,
int vintConnectionTimeout = 30) where T : new()
{
// do your stuff here and return T
}
Run Code Online (Sandbox Code Playgroud)
另外,对于公共类中的公共方法,我强烈建议不要在c#中使用可选参数.
使用方法重载指定默认值.原因是可选参数在c#中的工作方式:当调用带有可选参数的方法并省略可选参数时,它的默认值将被编译到方法调用中.因此,如果从另一个程序集调用此方法,省略一些可选参数 - 如下所示:
yourObjectReference.RunReturningVar(sql, true);
Run Code Online (Sandbox Code Playgroud)
c#编译器实际上将其转换为:
yourObjectReference.RunReturningVar(sql, true, 0, false, 30);
Run Code Online (Sandbox Code Playgroud)
这意味着如果您想要更改任何参数的默认值,则还应重新编译引用此参数的其他程序集.因此,更好的选择是使用方法重载:
public dynamic RunReturningVar(
string vstrSql,
bool connval,
double copyID,
bool corpVal,
int vintConnectionTimeout)
{
// do your stuff here
}
public dynamic RunReturningVar(
string vstrSql,
bool connval,
double copyID,
bool corpVal
)
{
return RunReturningVar(vstrSql, connval, copyID, corpVal, 30);
}
public dynamic RunReturningVar(
string vstrSql,
bool connval,
double copyID,
)
{
return RunReturningVar(vstrSql, connval, copyID, false);
}
Run Code Online (Sandbox Code Playgroud)
等等.