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

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



肥皂起泡泡
浏览 311回答 2
2回答

元芳怎么了

该变量dataTypeModel未在代码的任何位置声明。如果您想以通用方式返回,您应该执行以下操作:public DataTypeModel<T> GetDataType<T>(string str) where T : class&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; List<DataTypeDomain> dataTypeDomain = new List<DataTypeDomain>();&nbsp; &nbsp; &nbsp; &nbsp; _dataProvider.ExecuteCmd(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "config_select_by_key",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; inputParamMapper: delegate (SqlParameterCollection paramCol)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; paramCol.AddWithValue("@ConfigKey", str);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; singleRecordMapper: delegate (IDataReader reader, short set)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int i = 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; DataTypeModel<int> dataTypeModel = new DataTypeModel<int>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; string key = string.Format("Key{0}", i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; DataTypeDomain dtd = dataTypeDomain.Find(x => x.ConfigKey == key);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dataTypeModel.ConfigKey = dtd.ConfigKey;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dataTypeModel.ConfigValue = int.Parse(dtd.ConfigValue);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; &nbsp; &nbsp; return new DataTypeModel<T>()&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ConfigKey = "What your key is",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 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.&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; }然后在您的界面中:public interface IDataTypeService{&nbsp; &nbsp; 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>&nbsp; --> With this you can use `T` in all of the class/interface此外,如果你想指定一些T应该遵循的约束,你可以这样做:where T : class;&nbsp; --> In our case this allow us to cast the object to T该代码未经测试,但我想它应该可以工作。

qq_遁去的一_1

您不能T在接口定义中保持打开状态。你必须关闭类型DataTypeModel<SomeType>&nbsp;GetDataType(string&nbsp;str);
打开App,查看更多内容
随时随地看视频慕课网APP