小编Asd*_*dar的帖子

你能确定一般类型的大小吗?

有没有办法获得sizeof()通用类型?例如

public int GetSize<T>()
{
    return sizeof(T); //this wont work because T isn't assigned but is there a way to do this
}
Run Code Online (Sandbox Code Playgroud)

正如在例子中所说,以上是不可能的,但有没有办法让它工作?尝试过,public unsafe int但它没有改变任何东西.真的不想做点什么

public int GetSize<T>()
{
    if (typeof(T) == typeof(byte) || typeof(T) == typeof(sbyte))
    {
        return 1;
    }
    else if (typeof(T) == typeof(short) || typeof(T) == typeof(ushort) || typeof(T) == typeof(char))
    {
        return 2;
    }
    //and so on.
}
Run Code Online (Sandbox Code Playgroud)

c#

5
推荐指数
1
解决办法
520
查看次数

你能拆分一个字符串并保留拆分字符吗?

有没有办法分割字符串,但保留拆分字符,如果你这样做:

"A+B+C+D+E+F+G+H".Split(new char[] { '+' });

你得到

A
B
C
D
E
F
G
H
Run Code Online (Sandbox Code Playgroud)

有没有办法使用拆分,所以它将保留拆分字符:

A
+B
+C
+D
+E
+F
+G
+H
Run Code Online (Sandbox Code Playgroud)

或者如果你有+在前面A,然后

+A
+B
+C
+D
+E
+F
+G
+H
Run Code Online (Sandbox Code Playgroud)

c# split

1
推荐指数
2
解决办法
447
查看次数

你能用关键字作为参数吗?

有没有办法使用关键字作为参数?我想创建一个名为BytesToValue()的方法,它看起来像这样:

public static T BytesToValue<T>(byte[] buffer, T type)
{
    string retType = typeof(T).ToString();

    if (retType.Contains(".Byte"))
    {
        // code here.
    }
    else if (retType.Contains(".Int16"))
    {
       // code here.
    }
    // and so on with all other types.
}
Run Code Online (Sandbox Code Playgroud)

我希望T type参数只接受一个关键字,例如BytesToValue(new byte[] { 0, 0, 0, 0 }, float),有没有办法使用关键字作为参数?我知道这个例子不会工作,但有没有办法使它工作?如果没有那么我该怎么办?

c#

-1
推荐指数
1
解决办法
58
查看次数

标签 统计

c# ×3

split ×1