【问题标题】:What is the alternative to Debug.WriteLine for Xamarin Forms PCL in Visual Studio 2017 Community EditionVisual Studio 2017 社区版中 Xamarin Forms PCL 的 Debug.WriteLine 的替代方法是什么
【发布时间】:2017-10-28 03:02:10
【问题描述】:

Debug.WriteLine 似乎在 Visual Studio 2017 社区版中不起作用,如以下链接所述:Console.WriteLine does not output to Output Window in VS 2017

谁能建议 Xamarin Forms PCL 的替代方案? 当我从 PCL 中查看 Debug 对象时,我只看到 WriteLine 的方法,所以我很难了解如何附加到不同的 Listener。

当我查看 System.Diagnostics 命名空间的 Xamarin 文档时,它列出了许多我似乎无法从我的 PCL 中访问的方法和类。例如,缺少“TraceListener”类。这是正确的行为吗?

【问题讨论】:

    标签: xamarin uwp xamarin.forms xamarin.uwp


    【解决方案1】:

    System.Diagnostic.Debug.WriteLine() 在我使用 Visual Studio 2017 的 PCL 项目、.NET Standard 项目和 Xamarin.Android/Xamarin.iOS 项目中工作正常。

    你自己试过吗?

    System.Console.WriteLine() 但是在 PCL 项目中不起作用,尽管这与您正在使用的 IDE 无关,并且与 how PCL projects work 有更多关系,但在 Xamarin.Android/Xamarin.iOS 项目中起作用.如果您想在 PCL 项目中使用System.Console.WriteLine(),您可以通过各种方法访问本机代码。其中之一是DependencyService.Get<>()

    创建以下类:

    PCL:

    public interface IPlatformHelpers {
        void WriteLine(string text);
    }
    

    iOS 和安卓:

    [assembly: Dependency(typeof(PlatformHelpers))]
    
    namespace App.<iOS | Android> {
    
        public class PlatformHelpers : IPlatformHelpers {
    
            public void WriteLine(string text) {
                System.Console.WriteLine(text);
            }
        }
    }
    

    现在在您的 PCL 中,您可以这样做:

    IPlatformHelpers helper = DependencyService.Get<IPlatformHelpers>();
    
    helper.WriteLine("Angry BLAH!");
    

    有趣的是,System.Console.WriteLine() 似乎可以在 .NET Standard 项目中使用(至少对于 .NET Standard 1.3+),尽管我自己还没有真正尝试过。

    【讨论】:

    • 是的,我确实已经测试过了。您使用的是什么版本的 Visual Studio?我认为这个问题可能是 Visual Studio 2017 社区版所特有的,正如我在上面提到的链接中所讨论的那样。
    • 您的依赖服务方法可能是我需要的解决方法,并且似乎适用于 Android 项目。事实上,在 Android 实现中,我可以使用“System.Console.WriteLine”或“Android.Util.Log.Debug”。它们都在 VS 输出窗口中产生输出。但是,我在 UWP 项目中找不到任何工作。我在 UWP 中似乎找不到等效的“System.Console.WriteLine”。如果在 UWP 实现中使用“System.Diagnostics.Debug.WriteLine”,我不会得到任何输出。有什么想法吗?
    • @AntWaters 我正在运行 VS 2017 Professional,但没有使用 UWP 的经验。您是否尝试过使用Trace.WriteLine()Debug.WriteLine()Trace.WriteLine() 也由项目属性中配置的内容控制。右键单击您的 UWP 项目 -> 属性 -> 构建 -> 然后查找 Define DEBUG 常量(应检查 DEBUG 配置并取消选中 RELEASE 配置)和 Define TRACE 常量(应该检查 DEBUG 和 RELEASE 配置)。您说“似乎没有等价物”,这是否意味着它不会构建?
    • 感谢@hvaughan3 的建议,但没有进展。已经检查了这两个属性。是的,我的意思是,如果我尝试在 UWP 项目中使用Console.WriteLine,它将无法编译,并且智能感知找不到任何要包含的引用。这同样适用于Trace。相反,Debug.WriteLine 被发现并编译,但不产生任何输出。
    猜你喜欢
    • 2017-12-05
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 2018-06-13
    • 2023-04-08
    • 1970-01-01
    • 2017-08-01
    相关资源
    最近更新 更多