请问在 C# 中如何检查一个对象的类型是否是 anonymous type ?
public static bool IsAnonymousType(dynamic obj)
{
// Determine whether the obj is an anonymous type object
}
未完成的实现
static bool IsAnonymousType(dynamic obj)
{
var emptyAnonymousType = new { }.GetType().ToString(); // <>f__AnonymousType0
var currentAnonymousType = ((object)obj).GetType().ToString(); // <>f__AnonymousType1`1[System.String]
// TODO: 需要比较 currentAnonymousType 与 emptyAnonymousType 是否有相同的开头字符串 "<>f__AnonymousType"
throw new NotImplementedException();
}
Console.WriteLine(IsAnonymousType(new { Title = "ASP.NET Core" }));
实现了,通过 ReadOnlySpan.Slice 逐个字符比较
static bool IsAnonymousType(dynamic obj)
{
if (obj == null) return false;
var emptyAnonymousType = new { }.GetType().ToString();
var currentAnonymousType = ((object)obj).GetType().ToString();
return HasSamePrefix(currentAnonymousType, emptyAnonymousType, 8);
}
static bool HasSamePrefix(ReadOnlySpan<char> str1, ReadOnlySpan<char> str2, int minSameCharCount = 1)
{
int len = Math.Min(str1.Length, str2.Length);
int sameCharCount = 0;
for (int i = 0; i < len && str1.Slice(i, 1).SequenceEqual(str2.Slice(i, 1)); i++)
{
sameCharCount++;
}
return sameCharCount >= minSameCharCount;
}
Console.WriteLine(IsAnonymousType(new { Title = "ASP.NET Core" })); // True
Console.WriteLine(IsAnonymousType(new { })); // True
Console.WriteLine(IsAnonymousType("ASP.NET Core")); // False
Console.WriteLine(IsAnonymousType(new BlogPost { Title = "ASP.NET Core" })); // False
Console.WriteLine(IsAnonymousType(new ExpandoObject())); // False
class BlogPost
{
public string Title { get; set; }
}