16

我正在使用 C# 类,它在我的 Windows Store App (C#) 中运行良好。但是当我尝试在 Windows 运行时组件中使用它时,我收到以下错误:

Calculator.Calculate(System.DateTime)' 具有类型为“System.DateTime”的参数“dateTime”。“System.DateTime”不是有效的 Windows 运行时参数类型。

类中的示例对象:

public DateTime Calculate(DateTime dateTime)
{
   int dayNumberOfDateTime = ExtractDayNumber(dateTime);
   int sunRiseInMinutes = CalculateSunRiseInternal(tanSunPosition, differenceSunAndLocalTime);
   return CreateDateTime(dateTime, sunRiseInMinutes);
}

我怎样才能解决这个问题?问题是什么?

4

2 回答 2

30

当您创建 Windows 运行时组件时,您的组件可以由不受管理的语言使用,例如 Javascript 或 C++。显然,这些语言不知道如何生成正确的 System.DateTime,它是一种特定的 .NET 类型。

因此,此类组件必须仅使用本机 WinRT 类型,否则必须遵守 WinRT 中存在的限制。您从一开始就会遇到这样一个限制,即 WinRT 不支持实现继承。这需要您声明您的班级seal

本机 WinRT 类型与 .NET 类型非常不同。可以存储日期的真正运行时类型是 Windows.Foundation.DateTime。字符串实际上是一个 HSTRING 句柄。List 实际上是一个 IVector。等等。

Needless to say, if you would actually have to use those native types then your program wouldn't resemble a .NET program anymore. And you don't, the .NET 4.5 version of the CLR has a language projection built in. Code that automatically translates WinRT types to their equivalent .NET types. That translation has a few rough edges, some types cannot easily be substituted. But the vast majority of them map without trouble.

System.DateTime is one such rough edge. The language projection of Windows.Foundation.DateTime is System.DateTimeOffset. So simply solve your problem by declaring your method like this:

public DateTimeOffset Calculate(DateTimeOffset dateTime) {
    // etc..
}

The only other point worth noting is that this is only required for members that other code might use. Public members.

于 2012-12-08T16:00:44.483 回答
1

I was also facing the same issue in my Windows Runtime Component as below.

Severity Code Description Project File Line Suppression State
Error Method '.put_TxPower(System.SByte)' has parameter 'value' of type 'System.SByte'.  
System.SByte' is not a valid Windows Runtime parameter type.

As Lukasz Madon mentioned in the comment, changing the access modifier from the public to internal worked for me.

Before:

public sbyte TxPower { get; set; }

After:

internal sbyte TxPower { get; set; }
于 2018-11-28T09:21:28.903 回答