如果我有方法签名就好
public string myMethod<T>( ... )
Run Code Online (Sandbox Code Playgroud)
我怎样才能在方法中获取作为类型参数给出的类型的名称?我想做类似的事情typeof(T).FullName,但这确实有效......
Ree*_*sey 131
你的代码应该有效. typeof(T).FullName完全有效.这是一个完全编译的功能程序:
using System;
class Program
{
public static string MyMethod<T>()
{
return typeof(T).FullName;
}
static void Main(string[] args)
{
Console.WriteLine(MyMethod<int>());
Console.ReadKey();
}
}
Run Code Online (Sandbox Code Playgroud)
运行以上打印(按预期):
System.Int32
Run Code Online (Sandbox Code Playgroud)
此扩展方法输出非泛型类型的简单类型名称,并附加泛型类型的泛型参数列表。这适用于您无需担心内部泛型参数(如IDictionary<int, IDictionary<int, string>>.
using System;
using System.Linq;
namespace Extensions
{
public static class TypeExtensions
{
/// <summary>
/// Returns the type name. If this is a generic type, appends
/// the list of generic type arguments between angle brackets.
/// (Does not account for embedded / inner generic arguments.)
/// </summary>
/// <param name="type">The type.</param>
/// <returns>System.String.</returns>
public static string GetFormattedName(this Type type)
{
if(type.IsGenericType)
{
string genericArguments = type.GetGenericArguments()
.Select(x => x.Name)
.Aggregate((x1, x2) => $"{x1}, {x2}");
return $"{type.Name.Substring(0, type.Name.IndexOf("`"))}"
+ $"<{genericArguments}>";
}
return type.Name;
}
}
}
Run Code Online (Sandbox Code Playgroud)
你的代码应该可以工作。您还可以获取类的名称而不是包括命名空间的全名,例如:
using System;
namespace ConsoleApp1
{
class Program
{
public static string GettingName<T>() => typeof(T).Name;
public static string GettingFullName<T>() => typeof(T).FullName;
static void Main(string[] args)
{
Console.WriteLine($"Name: {GettingName<decimal>()}");
Console.WriteLine($"FullName: {GettingFullName<decimal>()}");
}
}
}
Run Code Online (Sandbox Code Playgroud)
运行上述程序的输出是:
Name: Decimal
FullName: System.Decimal
Run Code Online (Sandbox Code Playgroud)
typeof(T).Name并typeof(T).FullName正在为我工作。我得到类型作为参数传递。
| 归档时间: |
|
| 查看次数: |
46493 次 |
| 最近记录: |