为了账号安全,请及时绑定邮箱和手机立即绑定

在 C# 中编写泛型以返回数据类型

在 C# 中编写泛型以返回数据类型

C#
肥皂起泡泡 2022-06-12 14:52:50
需要一些关于编写 C# 泛型以从 SQL 数据库返回数据类型的指导。我正在从我的数据库中读取数据以从“SetKey”中获取数据类型。我可以将它们作为字符串返回,但我希望将它们转换为 int,在下面的这个特定示例中。这是我到目前为止所拥有的。在我评论过的地方遇到了几个错误。我在这方面相当新,所以任何输入或建议将不胜感激。谢谢!
查看完整描述

2 回答

?
元芳怎么了

TA贡献1798条经验 获得超7个赞

该变量dataTypeModel未在代码的任何位置声明。


如果您想以通用方式返回,您应该执行以下操作:


public DataTypeModel<T> GetDataType<T>(string str) where T : class

    {

        List<DataTypeDomain> dataTypeDomain = new List<DataTypeDomain>();

        _dataProvider.ExecuteCmd(

            "config_select_by_key",

            inputParamMapper: delegate (SqlParameterCollection paramCol)

            {

                paramCol.AddWithValue("@ConfigKey", str);

            },

            singleRecordMapper: delegate (IDataReader reader, short set)

            {

                int i = 0;

                DataTypeModel<int> dataTypeModel = new DataTypeModel<int>();

                string key = string.Format("Key{0}", i);

                DataTypeDomain dtd = dataTypeDomain.Find(x => x.ConfigKey == key);

                dataTypeModel.ConfigKey = dtd.ConfigKey;

                dataTypeModel.ConfigValue = int.Parse(dtd.ConfigValue);

            }

        );

        return new DataTypeModel<T>()

        {

            ConfigKey = "What your key is",

            ConfigValue = dataTypeDomain.First() as T //Supposing that the list only contains one config element , if not, you should change your method return type to a List<DataTypeModel<T>> and return a List doing this for each element.

        };

    }

然后在您的界面中:


public interface IDataTypeService

{

    DataTypeModel<T> GetDataType<T>(string str) where T : class;

}

快速说明


当您使用泛型时,您应该在以下方法上指定 T :


DataTypeModel<T> GetDataType<T>(string str) --> Only use T inside method scope

另一种声明方式T是在类/接口级别,例如:


public interface IDataTypeService<T>  --> With this you can use `T` in all of the class/interface

此外,如果你想指定一些T应该遵循的约束,你可以这样做:


where T : class;  --> In our case this allow us to cast the object to T

该代码未经测试,但我想它应该可以工作。


查看完整回答
反对 回复 2022-06-12
?
qq_遁去的一_1

TA贡献1725条经验 获得超7个赞

您不能T在接口定义中保持打开状态。你必须关闭类型

DataTypeModel<SomeType> GetDataType(string str);


查看完整回答
反对 回复 2022-06-12
  • 2 回答
  • 0 关注
  • 310 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号