Uri类不支持urn:
开箱即用的方案的特定解析器。也许可以理解,因为即使 NID 的比较规则指定它不区分大小写,比较两个 NSS 的规则也将取决于特定命名空间定义的规则,根据RFC 8141。
对于快速而肮脏的方法,您可以尝试使用Uri.Compare()方法。如果两个 URI 相等,它将返回零,否则返回非零。
var u1 = new Uri("URN:foo:a123,456");
var u2 = new Uri("urn:foo:a123,456");
var u3 = new Uri("urn:FOO:a123,456");
var u4 = new Uri("urn:nope:a123,456");
Console.WriteLine(Uri.Compare(u1, u2, UriComponents.AbsoluteUri, UriFormat.SafeUnescaped, StringComparison.OrdinalIgnoreCase)); // 0
Console.WriteLine(Uri.Compare(u1, u3, UriComponents.AbsoluteUri, UriFormat.SafeUnescaped, StringComparison.OrdinalIgnoreCase)); // 0
Console.WriteLine(Uri.Compare(u2, u3, UriComponents.AbsoluteUri, UriFormat.SafeUnescaped, StringComparison.OrdinalIgnoreCase)); // 0
Console.WriteLine(Uri.Compare(u3, u4, UriComponents.AbsoluteUri, UriFormat.SafeUnescaped, StringComparison.OrdinalIgnoreCase)); // -8
对于更冒险的方法,您可以按照以下方式进行操作。这需要仔细考虑才能正确实施。这段代码并不是要按原样使用,而是作为一个起点。
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
var u1 = new Urn("URN:foo:a123,456");
var u2 = new Urn("urn:foo:a123,456");
var u3 = new Urn("urn:foo:a123,456");
var u4 = new Urn("urn:FOO:a123,456");
var u5 = new Urn("urn:not-this-one:a123,456");
Console.WriteLine(u1 == u2); // True
Console.WriteLine(u3 == u4); // True
Console.WriteLine(u4 == u5); // False
}
public class Urn : Uri
{
public const string UrnScheme = "urn";
private const RegexOptions UrnRegexOptions = RegexOptions.Singleline | RegexOptions.CultureInvariant;
private static Regex UrnRegex = new Regex("^urn:(?<NID>[a-z|A-Z][a-z|A-Z|-]{0,30}[a-z|A-Z]):(?<NSS>.*)$", UrnRegexOptions);
public string NID { get; }
public string NSS { get; }
public Urn(string s) : base(s, UriKind.Absolute)
{
if (this.Scheme != UrnScheme) throw new FormatException($"URN scheme must be '{UrnScheme}'.");
var match = UrnRegex.Match(this.AbsoluteUri);
if (!match.Success) throw new FormatException("URN's NID is invalid.");
NID = match.Groups["NID"].Value;
NSS = match.Groups["NSS"].Value;
}
public override bool Equals(object other)
{
if (ReferenceEquals(other, this)) return true;
return
other is Urn u &&
string.Equals(NID, u.NID, StringComparison.InvariantCultureIgnoreCase) &&
string.Equals(NSS, u.NSS, StringComparison.Ordinal);
}
public override int GetHashCode() => base.GetHashCode();
public static bool operator == (Urn u1, Urn u2)
{
if (ReferenceEquals(u1, u2)) return true;
if (ReferenceEquals(u1, null) || ReferenceEquals(u2, null)) return false;
return u1.Equals(u2);
}
public static bool operator != (Urn u1, Urn u2)
{
if (ReferenceEquals(u1, u2)) return false;
if (ReferenceEquals(u1, null) || ReferenceEquals(u2, null)) return true;
return !u1.Equals(u2);
}
}
}