SQL 'in' キーワードに似た C# の短縮条件文
-
09-06-2019 - |
質問
C# では、これを簡単に記述する方法はありますか?
public static bool IsAllowed(int userID)
{
return (userID == Personnel.JohnDoe || userID == Personnel.JaneDoe ...);
}
のように:
public static bool IsAllowed(int userID)
{
return (userID in Personnel.JohnDoe, Personnel.JaneDoe ...);
}
switch を使用することもできることはわかっていますが、このような関数 (従来の ASP サイトを ASP.NET に移植する) を作成する必要がある関数がおそらく 50 個ほどあるので、できるだけ短くしたいと思います。
解決
これはどう?
public static class Extensions
{
public static bool In<T>(this T testValue, params T[] values)
{
return values.Contains(testValue);
}
}
使用法:
Personnel userId = Personnel.JohnDoe;
if (userId.In(Personnel.JohnDoe, Personnel.JaneDoe))
{
// Do something
}
これの功績を主張することはできませんが、どこで見たのかも思い出せません。したがって、匿名のインターネットの見知らぬ人、あなたに敬意を表します。
他のヒント
次のようなものはどうでしょうか。
public static bool IsAllowed(int userID) {
List<int> IDs = new List<string> { 1,2,3,4,5 };
return IDs.Contains(userID);
}
(もちろん、ニーズに応じて、静的ステータスを変更したり、他の場所で ID クラスを初期化したり、IEnumerable<> を使用したりすることもできます。重要な点は、次のものに最も近いものであるということです。 で SQL の演算子は Collection.Contains() 関数です。)
許可された ID のリストを次のようにカプセル化します。 データ ない コード. 。そうすれば、ソースは後で簡単に変更できます。
List<int> allowedIDs = ...;
public bool IsAllowed(int userID)
{
return allowedIDs.Contains(userID);
}
.NET 3.5を使用している場合は、次を使用できます IEnumerable
の代わりに List
拡張メソッドのおかげで。
(この関数は静的であってはなりません。この投稿を参照してください: 静電気を使いすぎると悪いのか良いのか?.)
権限はユーザー ID に基づいていますか?その場合は、ロールベースのアクセス許可を使用することで、より良い解決策が得られる可能性があります。あるいは、「許可されたユーザー」リストにユーザーを追加するために、そのメソッドを頻繁に編集する必要がある場合があります。
たとえば、enum userrole {ユーザー、管理者、司会者}
class User {
public UserRole Role{get; set;}
public string Name {get; set;}
public int UserId {get; set;}
}
public static bool IsAllowed(User user) {
return user.Role == UserRole.LordEmperor;
}
素敵なちょっとしたトリックは、次のように通常の .Contains() の使用方法を逆にすることです。
public static bool IsAllowed(int userID) {
return new int[] { Personnel.JaneDoe, Personnel.JohnDoe }.Contains(userID);
}
配列に好きなだけエントリを入れることができます。
Personnel.x が列挙型の場合、これ (および投稿した元のコード) でキャストの問題が発生する可能性があります。その場合は、次の方が使いやすいでしょう。
public static bool IsAllowed(int userID) {
return Enum.IsDefined(typeof(Personnel), userID);
}
私が考えることができる最も近いものは次のとおりです。
using System.Linq;
public static bool IsAllowed(int userID)
{
return new Personnel[]
{ Personnel.JohnDoe, Personnel.JaneDoe }.Contains((Personnel)userID);
}
人事用のイテレータを作成できますか。
public static bool IsAllowed(int userID)
{
return (Personnel.Contains(userID))
}
public bool Contains(int userID) : extends Personnel (i think that is how it is written)
{
foreach (int id in Personnel)
if (id == userid)
return true;
return false;
}
別の構文のアイデア:
return new [] { Personnel.JohnDoe, Personnel.JaneDoe }.Contains(userID);