簡體   English   中英

如何在函數中創建 IDataParameter 並返回它?

[英]How can I create IDataParameter in a function and return it?

我不知道這個問題是如何正確的,但我的項目條件是我需要一個函數來獲取值和參數名稱並返回一個參數以在某些命令中使用。
我正在考慮的原型是這樣的:

public IDataParameter CreateParameter(string parameterName, object value)

無論如何,這是要做到這一點嗎?

感謝@nvoigt,我為它創建了一個從 IDBDataParameter 派生的類
我根據我的要求添加了兩個構造函數。

public class MyClass: IDbDataParameter
{
    public MyClass(string parameterName, object value)
    {
        ParameterName = parameterName;
        Value = value;
    }
    public MyClass(string parameterName, object value, DbType dbType)
    {
        ParameterName = parameterName;
        Value = value;
        DbType = dbType;
    }
    public DbType DbType { get; set; }
    public ParameterDirection Direction { get; set; }
    public bool IsNullable => throw new NotImplementedException();
    public string ParameterName { get; set; }
    public string SourceColumn { get; set; }
    public DataRowVersion SourceVersion { get; set; }
    public object Value { get; set; }
    public byte Precision { get; set; }
    public byte Scale { get; set; }
    public int Size { get; set; }
}


並在這樣的方法中使用它們:

public IDbDataParameter CreateParameter(string parameterName, object value)
    {
        return new MyClass(parameterName, value);
    }


雖然您當然可以這樣做,但這意味着您需要將要為返回值實例化的類硬編碼到您的函數

最好是傳入命令,因為他們應該知道他們需要什么類型的參數。

例子:

public IDbDataParameter CreateParameter(IDbCommand command, string parameterName, object value)
{
    var parameter = command.CreateParameter();

    parameter.ParameterName = parameterName;
    parameter.Value = value;

    return parameter;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM