c#Type数组转成字符串的名称

private static readonly Type[] types = new[] { typeof(Class1), typeof(Class2) }; 把types 转铁成字符串

我需要将 Type 数组转换为字符串。有几种常见的转换方式:1. 获取类型的全名数组 2. 获取类型的简单名称数组 3. 将类型信息格式化为更详细的字符串 4. 转换为 JSON 格式。我将提供这些不同的转换方法。

Type 数组转换为字符串的多种方法

以下是将Type[]数组转换为字符串的几种实用方法:

方法 1:获取类型全名数组

csharp

运行

复制代码
private static readonly Type[] types = new[] { typeof(Class1), typeof(Class2) };

// 转换为类型全名数组
public static string[] GetTypeFullNames()
{
    return types.Select(t => t.FullName).ToArray();
}

// 使用示例
var fullNames = GetTypeFullNames();
Console.WriteLine(string.Join(", ", fullNames));
// 输出: YourNamespace.Class1, YourNamespace.Class2

方法 2:获取类型简单名称数组

csharp

运行

复制代码
// 转换为类型简单名称数组
public static string[] GetTypeNames()
{
    return types.Select(t => t.Name).ToArray();
}

// 使用示例
var names = GetTypeNames();
Console.WriteLine(string.Join(", ", names));
// 输出: Class1, Class2

方法 3:转换为单个字符串(逗号分隔)

csharp

运行

复制代码
// 转换为单个逗号分隔的字符串
public static string GetTypesAsString()
{
    return string.Join(", ", types.Select(t => t.Name));
}

// 使用示例
var typesString = GetTypesAsString();
Console.WriteLine(typesString);
// 输出: Class1, Class2

方法 4:转换为详细信息字符串

csharp

运行

复制代码
// 转换为包含详细信息的字符串
public static string GetTypesDetails()
{
    return string.Join(Environment.NewLine, types.Select(t => 
        $"Type: {t.Name}{Environment.NewLine}" +
        $"FullName: {t.FullName}{Environment.NewLine}" +
        $"Namespace: {t.Namespace}{Environment.NewLine}" +
        $"Assembly: {t.Assembly.GetName().Name}"));
}

// 使用示例
var details = GetTypesDetails();
Console.WriteLine(details);
// 输出详细的类型信息

方法 5:转换为 JSON 格式

csharp

运行

复制代码
using System.Text.Json;

// 转换为JSON字符串
public static string GetTypesAsJson()
{
    var typeInfo = types.Select(t => new
    {
        Name = t.Name,
        FullName = t.FullName,
        Namespace = t.Namespace,
        Assembly = t.Assembly.GetName().Name
    });
    
    return JsonSerializer.Serialize(typeInfo, new JsonSerializerOptions
    {
        WriteIndented = true
    });
}

// 使用示例
var json = GetTypesAsJson();
Console.WriteLine(json);
// 输出格式化的JSON

方法 6:转换为查找字典

csharp

运行

复制代码
// 创建类型名称到Type对象的映射字典
public static Dictionary<string, Type> GetTypeDictionary()
{
    return types.ToDictionary(t => t.Name, t => t, 
        StringComparerOrdinalIgnoreCase);
}

// 使用示例
var typeDict = GetTypeDictionary();
if (typeDict.TryGetValue("class1", out var type))
{
    Console.WriteLine($"Found type: {type.FullName}");
}

完整示例

csharp

运行

复制代码
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text.Json;

public class Program
{
    private static readonly Type[] types = new[] { typeof(Class1), typeof(Class2) };

    public static void Main()
    {
        Console.WriteLine("=== 类型全名 ===");
        Console.WriteLine(string.Join(", ", types.Select(t => t.FullName)));
        
        Console.WriteLine("\n=== 类型名称 ===");
        Console.WriteLine(string.Join(", ", types.Select(t => t.Name)));
        
        Console.WriteLine("\n=== JSON格式 ===");
        Console.WriteLine(GetTypesAsJson());
        
        Console.WriteLine("\n=== 查找字典 ===");
        var dict = GetTypeDictionary();
        Console.WriteLine($"查找 'Class1': {dict["Class1"].FullName}");
        Console.WriteLine($"查找 'class2' (忽略大小写): {dict["class2"].FullName}");
    }
    
    public static string GetTypesAsJson()
    {
        var typeInfo = types.Select(t => new
        {
            Name = t.Name,
            FullName = t.FullName,
            Namespace = t.Namespace
        });
        
        return JsonSerializer.Serialize(typeInfo, new JsonSerializerOptions
        {
            WriteIndented = true
        });
    }
    
    public static Dictionary<string, Type> GetTypeDictionary()
    {
        return types.ToDictionary(t => t.Name, t => t, 
            StringComparerOrdinalIgnoreCase);
    }
}

public class Class1 { }
public class Class2 { }

这些方法提供了灵活的 Type 数组到字符串的转换选项,可以根据具体需求选择合适的方法。

var typeInfo = types.Select(t => new { Name = t.Name, FullName = t.FullName, Namespace = t.Namespace }); 如何加一个ID序号,

我需要在现有的 LINQ 查询中为每个类型信息添加一个序号。可以使用 Select 的重载方法,它接受索引参数,这样就能为每个元素添加序号了。

为 Type 信息添加序号的多种方法

方法 1:使用 Select 的索引重载

csharp

运行

复制代码
var typeInfo = types.Select((t, index) => new
{
    Id = index + 1, // 从1开始的序号
    Name = t.Name,
    FullName = t.FullName,
    Namespace = t.Namespace
});

方法 2:使用匿名类型和索引

csharp

运行

复制代码
var typeInfo = types.Select((type, idx) => new
{
    ID = idx + 1,
    TypeName = type.Name,
    FullTypeName = type.FullName,
    TypeNamespace = type.Namespace
});

方法 3:使用记录类型(C# 90+)

csharp

运行

复制代码
public record TypeInfo(int Id, string Name, string FullName, string Namespace);

var typeInfo = types.Select((t, index) => new TypeInfo(
    Id: index + 1,
    Name: t.Name,
    FullName: t.FullName,
    Namespace: t.Namespace
));

方法 4:使用 List.ForEach 添加序号

csharp

运行

复制代码
var typeInfoList = new List<dynamic>();
types.ToList().ForEach((t, index) =>
{
    typeInfoList.Add(new
    {
        Id = index + 1,
        Name = t.Name,
        FullName = t.FullName,
        Namespace = t.Namespace
    });
});

方法 5:使用循环手动添加序号

csharp

运行

复制代码
var typeInfoList = new List<object>();
for (int i = 0; i < types.Length; i++)
{
    var t = types[i];
    typeInfoList.Add(new
    {
        Id = i + 1,
        Name = t.Name,
        FullName = t.FullName,
        Namespace = t.Namespace
    });
}

完整示例

csharp

运行

复制代码
using System;
using System.Linq;
using System.Text.Json;

public class Program
{
    private static readonly Type[] types = new[] { typeof(Class1), typeof(Class2), typeof(Class3) };

    public static void Main()
    {
        // 添加序号的类型信息
        var typeInfo = types.Select((t, index) => new
        {
            Id = index + 1,
            Name = t.Name,
            FullName = t.FullName,
            Namespace = t.Namespace
        });

        // 转换为JSON显示
        var json = JsonSerializer.Serialize(typeInfo, new JsonSerializerOptions
        {
            WriteIndented = true
        });

        Console.WriteLine(json);

        // 或者直接遍历显示
        Console.WriteLine("\n类型信息列表:");
        foreach (var info in typeInfo)
        {
            Console.WriteLine($"ID: {info.Id}, 名称: {info.Name}, 命名空间: {info.Namespace}");
        }
    }
}

public class Class1 { }
public class Class2 { }
public class Class3 { }

输出示例

json

复制代码
[
  {
    "Id": 1,
    "Name": "Class1",
    "FullName": "YourNamespace.Class1",
    "Namespace": "YourNamespace"
  },
  {
    "Id": 2,
    "Name": "Class2",
    "FullName": "YourNamespace.Class2",
    "Namespace": "YourNamespace"
  },
  {
    "Id": 3,
    "Name": "Class3",
    "FullName": "YourNamespace.Class3",
    "Namespace": "YourNamespace"
  }
]

类型信息列表:
ID: 1, 名称: Class1, 命名空间: YourNamespace
ID: 2, 名称: Class2, 命名空间: YourNamespace
ID: 3, 名称: Class3, 命名空间: YourNamespace

最推荐的是方法 1 ,它简洁高效,是 LINQ 的标准用法。如果需要在多个地方复用这个结构,可以考虑方法 3使用记录类型。

输入需求,零门槛生成网站、工具或游戏

模板

参考图

画板

相关推荐
毕设源码李师姐18 小时前
计算机毕设 java 基于 java 的图书馆借阅系统 智能图书馆借阅综合管理平台 基于 Java 的图书借阅与信息管理系统
java·开发语言·课程设计
忆~遂愿18 小时前
Runtime 上下文管理:计算实例的生命周期、延迟最小化与上下文切换优化
java·大数据·开发语言·人工智能·docker
沐知全栈开发18 小时前
PostgreSQL中的AND和OR操作符
开发语言
powerfulhell18 小时前
寒假python作业5
java·前端·python
1尢晞118 小时前
Java学习
java·开发语言
阿杰真不会敲代码18 小时前
Mybatis-plus入门到精通
java·tomcat·mybatis
木井巳18 小时前
【递归算法】二叉搜索树中第K小的元素
java·算法·leetcode·深度优先·剪枝
毕设源码-赖学姐18 小时前
【开题答辩全过程】以 基于python的电影推荐系统为例,包含答辩的问题和答案
开发语言·python
qq_2975746718 小时前
【实战】POI 实现 Excel 多级表头导出(含合并单元格完整方案)
java·spring boot·后端·excel
星辰_mya18 小时前
Elasticsearch线上问题之慢查询
java·开发语言·jvm