将T转换为long

本文关键字:long 转换 | 更新日期: 2023-09-27 17:54:46

我有一个通用类(c#),

class MyClass<T> where T : struct, IComparable<T>
{
    public T filelocation;
}

T可以是UInt32,也可以是UInt64。

我需要将文件位置转换为长格式,以便在文件中查找…

我已经尝试了以下

long loc = (T)myclass.filelocation;
long loc = (T)(object)myclass.filelocation;

但似乎什么都不起作用…

任何想法?

将T转换为long

Call Convert.ToInt64 .

写入(object)fileLocation创建一个盒装的UInt32
已装箱的值类型只能被解装箱为它们的原始值类型,因此您不能一步将其强制转换为long
您可以编写(long)(ulong)fileLocation,但由于同样的原因,uint将失败。

Try Convert.ToInt64.

long loc = Convert.ToInt64(myclass.filelocation);

您可以使用TryParse:

long lng;
int testNum = 55;
long.TryParse(testNum.ToString(),out lng);

与你的类定义如果我写这样的东西

public MyClass<long> myclass = new MyClass<long>();
    public long returnLong() 
            {
                return myclass.filelocation;
            }

myclass。fileLocation默认返回long