简体   繁体   English

如何在函数中创建 IDataParameter 并返回它?

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

I don't know how this question is correct but my project condition is that I need a function that get value and parameter name and return a Parameter for using in some commands.我不知道这个问题是如何正确的,但我的项目条件是我需要一个函数来获取值和参数名称并返回一个参数以在某些命令中使用。
The prototype that I am thinking on it is like this :我正在考虑的原型是这样的:

public IDataParameter CreateParameter(string parameterName, object value)

Is this anyway to do that ?无论如何,这是要做到这一点吗?

Thanks to @nvoigt I created a class for it that derivative from IDBDataParameter感谢@nvoigt,我为它创建了一个从 IDBDataParameter 派生的类
I added two constructor based on my requirement.我根据我的要求添加了两个构造函数。

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; }
}


and use them in a method like this :并在这样的方法中使用它们:

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


While you certainly can do that, it would mean you'd need to hard code into your function which class you want to instantiate for your return value.虽然您当然可以这样做,但这意味着您需要将要为返回值实例化的类硬编码到您的函数

Better would be to pass in the commands, because they should know what type of parameter they need.最好是传入命令,因为他们应该知道他们需要什么类型的参数。

Example:例子:

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