【问题标题】:Is possible create a method with an undefined type?是否可以创建一个未定义类型的方法?
【发布时间】:2016-07-10 04:09:25
【问题描述】:

我正在尝试为连接到外部数据库的 WebService 创建一个“插入”方法,但我没有创建 InsertPerson、InsertAge、Insert 任何东西,而是尝试做一个独特的插入,参数类型是根据请求自动定义的,例如:如果我想在 db 中插入一个人,我调用 Insert("mytype" name),如果在我想插入年龄之后调用 Insert("mytype" age) 并且当您单击特定按钮时会包含此类型。

如果令人困惑,我将尝试再用一个示例进行解释:我单击“插入年龄”按钮,该按钮将通过参数发送到“mytype”,这是一个整数和文本框的值,代码将连接到数据库并插入那。像这样的:

点击事件 -> mytype = int
Insert(int age) -> "INSERT INTO db VALUE age"

那么,毕竟,有可能创造出这样的东西吗?还是有其他更好的选择?

【问题讨论】:

    标签: c# database visual-studio web-services


    【解决方案1】:

    不用在object 中装箱,您可以通用:

    public void Insert<T>(T input)
    {
        // DB setup code goes here
        var parameter = new SqlParameter("@input", input);
    
        // Finish DB code here
    }
    
    // Call it like this
    myClass.Insert<int>(integerInputData);
    myClass.Insert<string>(stringInputData);
    

    它比对象中的装箱和拆箱更干净。

    https://msdn.microsoft.com/en-us/library/twcad0zb.aspx

    但是,如果您只是将它传递给需要 object 的东西(例如 SqlParameter),那么您可以将其装箱到 object

    public void Insert(object input)
    {
       // DB setup code goes here
       var parameter = new SqlParameter("@input", input);
    
       // Finish DB code here
    }
    
    // Call it like this
    myClass.Insert(integerInputData);
    myClass.Insert(stringInputData);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-27
      • 2016-12-23
      • 1970-01-01
      • 2021-06-30
      • 1970-01-01
      • 1970-01-01
      • 2020-04-20
      相关资源
      最近更新 更多