'System.DateTime' is not a valid Windows Runtime parameter type

前端 未结 2 932
南旧
南旧 2021-02-05 11:33

I\'m using a C# class and it works perfectly fine in my Windows Store App (C#). But when I try to use it in a Windows Runtime Compenent I get the following error:

2条回答
  •  星月不相逢
    2021-02-05 12:35

    When you create a Windows Runtime Component then your component can be used by languages that are not managed, like Javascript or C++. Clearly those languages have no idea how to generate a proper System.DateTime, it is a specific .NET type.

    Such components must therefore only use native WinRT types and otherwise observe the restrictions present in WinRT. One such restriction you'll run into from the get-go is that WinRT does not support implementation inheritance. Which requires you to declare your class sealed.

    The native WinRT types are very unlike the .NET types. The real runtime type that can store a date is Windows.Foundation.DateTime. A string is actually an HSTRING handle. A List is actually an IVector. Etcetera.

    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.

提交回复
热议问题