我提供了一个方法,该方法接受三个bool参数并返回一个字符串值。例如,我将0,1,2保存在表列中。我有三个布尔变量isView
,isAddUpdate
和isDelete
。当isView
为true
时,仅保存0,如果isView
和isAddUpdate
为真,则保存为0.1,如果全部为真,则保存为0,1,2
这是我的代码。请建议我一个更好的方法来实现这一目标。
public string getActions(bool isView, bool isAddupdate, bool isDelete)
{
try
{
var _val = "";
if (isView && isAddupdate && isDelete)
_val = "0,1,2";
if (isView && isAddupdate && !isDelete)
_val = "0,1";
if (isView && !isAddupdate && !isDelete)
_val = "0";
if (!isView && !isAddupdate && !isDelete)
_val = "";
if (!isView && !isAddupdate && isDelete)
_val = "2";
if (!isView && isAddupdate && isDelete)
_val = "1,2";
return _val;
}
catch (Exception ex)
{
throw ex;
}
}
答案 0 :(得分:7)
也许是这样?
public string getActions(bool isView, bool isAddupdate, bool isDelete)
{
var codes = new List<int>();
if (isView) codes.Add(0);
if (isAddupdate) codes.Add(1);
if (isDelete) codes.Add(2);
return string.Join(",", codes);
}
答案 1 :(得分:1)
public string getActions(bool isView, bool isAddupdate, bool isDelete)
{
string[] values = new string[3];
if (isView)
values[0] = "0";
if (isAddupdate)
values[1] = "1";
if (isDelete)
values[2] = "2";
return String.Join(",", values.Where(s => !string.IsNullOrEmpty(s)));
}
我删除了try/catch
块。我没有看到任何原因。
答案 2 :(得分:1)
也许是另一种方法,但是尝试使用[Flags]
枚举
类似的事情通常可能会有所帮助
[Flags]
. public enum Actions
. {
. None = 0,
. View = 1,
. AddUpdate = 2,
. Delete = 4
. }
如果您想坚持使用布尔输入
public string getActions(bool isView, bool isAddUpdate, bool isDelete)
{
var a = isView ? Actions.View : Actions.None;
a |= isAddUpdate ? A.AddUpdate : Actions.None;
a |= isDelete ? Actions.Delete : Actions.None;
return a.ToString();
}
假设isView
为真,isAddUpdate
为假,isDelete
为真,则返回
"View, Delete"
答案 3 :(得分:0)
如果您正在使用诸如SQL Server,MySql或PostgreSQL之类的关系数据库,那么我建议您将这些值存储为位,因为它比存储3个字符串便宜。
但是,如果您需要这样做,或者如果使用的是MongoDB之类的东西,那么我建议使用此解决方案,不要存储1,2,3个存储二进制字符(1或0)以准确表示布尔值。
请参阅下面的代码以获取说明:
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var stringvalue = getActions(false, true, false); //this result you store to your db
Console.WriteLine(stringvalue);
Console.ReadLine();
var deserialised = DeserialiseActions(stringvalue); //you would have retrieved this from the database
}
public static string getActions(bool isView, bool isAddupdate, bool isDelete)
{
return $"{Convert.ToSByte(isView).ToString()}{Convert.ToSByte(isAddupdate).ToString()}{Convert.ToSByte(isDelete).ToString()}";
}
public static ActionsCollection DeserialiseActions(string dataValue)
{
return new ActionsCollection
{
IsView = bool.Parse(dataValue[0].ToString()),
IsUpdate = bool.Parse(dataValue[1].ToString()),
IsDelete = bool.Parse(dataValue[2].ToString())
};
}
}
class ActionsCollection
{
public bool IsView { get; set; }
public bool IsUpdate { get; set; }
public bool IsDelete { get; set; }
}
}