C#从字符串变量中获取类型并在泛型方法中使用它(C# Getting Type out of a string variable and using it in generic method)

C#从字符串变量中获取类型并在泛型方法中使用它(C# Getting Type out of a string variable and using it in generic method)

 

I want to be able to get the actual Type of a string value I receive by some means (i.e from database) so I can use that Type in generic method like DoSomething<Type>().

In my project, I have classes Plane, and Car located in MyCompany.MySolution.Vehicle namespace like so

- MyCompany.MySolution.Vehicle
  |+Interfaces
  |-Implementations
    |-Car
    |-Plane

I receive type of the vehicle as a string. So, I get string "Car" which means, I need to get Type Car so I can use that type in a generic method to register it like so:

MyFactory.Register<Car>(carId)

So, MyFactory is static class calling Register() method.

Similarly, I receive string "Plane" which means, I need to get Type Plane so I can use that type in the generic method above to register a Plane.

I tried using something like

MyFactory.Register<Type.GetType("MyCompany.MySolution.Vehicle.Implementations.Car")>(carId)

,but that does not work.

解决方案

If you want to invoke a Generic Method with a Type parameter generate at Runtime, you could do something like this:

var vehicleString = "Car";

// use the fully-qualified name of the type here
// (assuming Car is in the same assembly as this code, 
//  if not add a ", TargetAssemblyName" to the end of the string)
var vehicleType = 
    Type.GetType($"MyCompany.MySolution.Vehicle.Implementations.{vehicleString}");

// assuming MyFactory is the name of the class 
// containing the Register<T>-Method
typeof(MyFactory).GetMethod("Register")
    .MakeGenericMethod(vehicleType)
    .Invoke(this);

Working Example

Just as a note:

This is not how generics are supposed to be used. I'm just pointing out the possibility, not giving you an ideal answer to the problem you're proposing. Maybe you should rethink some of your architectural design choices!

我希望能够以某种方式(即从数据库)获取我接收到的字符串值的实际类型,因此我可以在 DoSomething< Type>()<等通用方法中使用该类型/ code>。

在我的项目中,我有 Plane 和 Car 位于 MyCompany.MySolution.Vehicle 命名空间中,像这样

 -MyCompany.MySolution.Vehicle 
 | +接口
 |-实现
 |-汽车
 |-飞机

我以字符串形式接收车辆的类型。因此,我得到字符串" Car",这意味着,我需要获取Type Car ,以便可以在通用方法中使用该类型进行注册,如下所示:

  MyFactory.Register< Car>(carId)

因此,MyFactory是调用Register()方法的静态类。

同样,我收到字符串" Plane",这意味着,我需要获取键入 Plane ,这样我就可以在上面的通用方法中使用该类型来注册飞机。

我尝试使用某些方法像

  MyFactory.Register< Type.GetType(" MyCompany.MySolution.Vehicle.Implementations.Car")>(carId) 

,但这不起作用。

解决方案

如果要使用在运行时生成的Type参数调用泛型方法,则可以进行如下操作:

  var vehicleString =" Car"; 
 
 //在此处使用该类型的标准名称
 //(假设Car与该代码位于同一程序集中,
 //如果未添加", TargetAssemblyName"到字符串的末尾)
 var vehicleType = 
 Type.GetType($" MyCompany.MySolution.Vehicle.Implementations。{vehicleString}"); 
 
 //假设MyFactory是类
 //包含Register< T>-方法
 typeof(MyFactory).GetMethod(" Register").MakeGenericMethod(vehicleType)
 .Invoke(this); 

这是 不是 。应该如何使用泛型。我只是指出可能性,而不是为您提出的问题提供理想的答案。也许您应该重新考虑一些建筑设计选择!

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
生成 SQL Server 建表语句的过程需要考虑以下几个因素: 1. 表名:根据泛型类型名称生成表名。 2. 字段名:根据泛型类型的属性名称生成对应的列名。 3. 字段类型:根据泛型类型的属性数据类型生成对应的 SQL Server 数据类型。 4. 主键:根据泛型类型定义的主键属性生成主键列。 以下是一个示例的 C# 代码,用于根据泛型类型生成 SQL Server 建表语句: ```csharp public static string GenerateCreateTableSql<T>() { var tableName = typeof(T).Name; var properties = typeof(T).GetProperties(); var primaryKey = properties.FirstOrDefault(p => p.GetCustomAttribute<KeyAttribute>() != null); var sb = new StringBuilder(); sb.AppendLine($"CREATE TABLE {tableName} ("); foreach (var property in properties) { var columnName = property.Name; var columnType = GetSqlType(property.PropertyType); sb.AppendLine($"\t{columnName} {columnType},"); if (primaryKey != null && primaryKey.Name == property.Name) { sb.AppendLine($"\tPRIMARY KEY ({columnName}),"); } } sb.Remove(sb.Length - 3, 1); sb.AppendLine("\n);"); return sb.ToString(); } private static string GetSqlType(Type type) { if (type == typeof(int)) { return "INT"; } else if (type == typeof(string)) { return "NVARCHAR(MAX)"; } // 其他数据类型的判断 throw new NotImplementedException($"Type {type.FullName} is not supported."); } ``` 通过调用 `GenerateCreateTableSql<T>` 方法传入泛型类型参数即可生成对应的 SQL Server 建表语句。例如: ```csharp var sql = GenerateCreateTableSql<User>(); ``` 将生成如下 SQL 语句: ```sql CREATE TABLE User ( Id INT, Name NVARCHAR(MAX), Age INT, PRIMARY KEY (Id) ); ``` 其,`User` 类型定义如下: ```csharp public class User { [Key] public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值