我正在转换旧的经典 ASP 方法来记录数据。其中一个参数可以是数组或字符串。我要声明什么类型的变量?我试着将它声明为一个对象,然后测试它是否是一个数组。但是,我似乎无法解析出数组内容(应该是一个简单的字符串数组)。
这是一段经典的 ASP 代码:
Public function security(u,a,d)
' -------------------------------------------------------
' Write to tbl_log_security, returning a 1-Pass or 0-Fail
' -------------------------------------------------------
u = u + 0
af = u
if len(request.Cookies("userid")) > 0 then af = request.Cookies("userid")
security = 1 ' Success
Dim objCommandLog
Set objCommandLog = Server.CreateObject("ADODB.Connection")
objCommandLog.open = application("connVRVprimary")
Err.Clear
if isarray(d) then
for I = 0 to ubound(d)
strDetails = strDetails & chr(13) & "Detail " & I & ": " & d(i) & " "
next
elseif len(d) > 0 then : strDetails = d & " "
end if
这里是我认为它可能会转换为 C# 的方式。
public static bool security(string UserID, string Action, object Details )
{
// Apparently, Details can be a string or an array !
// UserID is passed in as a string, we need to convert it to an int
Int32 iUserID; //af
string strDetails;
if (!Int32.TryParse(UserID, out iUserID))
{
//If it doesn't convert, then use the UserID from Application Object
iUserID = Convert.ToInt32(ApplicationObject.USERID);
}
Type valueType = Details.GetType();
if (valueType.IsArray)
{
for(int i = 0, i < Details.Length; i++)
{
strDetails += "Detail " + i + ": " + Details(i);
}
}
else
{ // is string
strDetails = Details;
}
Intellisense 告诉我无法获取长度属性或遍历它。我怀疑即使认为它可能作为一个数组出现,它也被视为一个对象。 任何帮助将不胜感激。
最佳答案
"One of the parameters could be an Array or a string. What type of variable do I declare?"
params
助您一臂之力!
由于 details
是方法签名中的最后一个参数,您可以将其定义为 params
参数,它允许传递任意数量的项目。
(旁注:在 C# 中,方法名称通常是 PascalCase
,参数通常是 camelCase
)
public static bool Security(string userID, string action, params string[] details )
{
// Other code omitted for brevity
var strDetails = details == null ? " "
: details.Length == 1 ? $"{details[0]} "
: string.Join(Environment.NewLine,
details.Select((detail, index) => $"Detail {index}: {detail} "));
}
关于c# - 创建一个方法,其中一个参数可以是数组或字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58034622/