小编Eri*_*ips的帖子

没有访客模式的动态调度

问题

我正在使用已经存在的库,以及我无法访问的源代码.该库代表AST.

我想复制此AST的部分内容,但重命名过程中对变量的引用.由于可以有一个包含Expression对象的AssignCommand-Object,我希望能够使用自己的函数复制每个对象,因此我可以递归地调用它们.但是,由于我无法访问库的代码,我无法添加诸如此类的方法CopyAndRename(string prefix).

因此,我的方法是创建一个Rename具有多个重载的单个函数.因此,我的家庭功能如下:

public static Command Rename(Command cmd, string prefix)
public static AssignCommand Rename(AssignCommand cmd, string prefix)
public static AdditionExpressionRename(AdditionExpression expr, string prefix)
....
Run Code Online (Sandbox Code Playgroud)

函数现在由a组成List<Command>,where AssignCommand是其子类Command.我假设我可以只传递CommandRename-function,运行时会找到最具体的一个.但是,情况并非如此,所有命令都会传递给Command Rename(Command cmd, string prefix).为什么会这样?有没有办法将调用委托给正确的函数而不使用丑陋的is操作?

最小的例子

我已将此问题解决为以下NUnit-Testcode

using NUnit.Framework;

public class TopClass{
    public int retVal;
}

public class SubClassA : TopClass{ }

[TestFixture]
public class ThrowawayTest {


    private TopClass Foo (TopClass x) {
        x.retVal = 1; …
Run Code Online (Sandbox Code Playgroud)

c# polymorphism mono overloading dynamic-dispatch

11
推荐指数
1
解决办法
2987
查看次数

使用Angular验证模糊的输入字段

我做了一个简单的测试输入字段,但我想确认转换上的模糊,但我没有任何想法要实现这一目标,因为我不是这样熟悉angularjs.

任何人帮我验证这个例子中只有一个模糊请...

myJs:

angular.module('myApp', [])
.controller('FormController', function($scope) {
  $scope.fields = [
    {placeholder: 'Username', isRequired: true},
    {placeholder: 'Password', isRequired: true},
    {placeholder: 'Email (optional)', isRequired: false}
  ];

  $scope.submitForm = function() {
    alert("it works!");
  };
});
Run Code Online (Sandbox Code Playgroud)

HTML:

<div ng-app="myApp">
<form name="signup_form" ng-controller="FormController" ng-submit="submitForm()" novalidate>
  <div ng-repeat="field in fields" ng-form="signup_form_input">
    <input type="text"
           name="dynamic_input"
           ng-required="field.isRequired"
           ng-model="field.name"
           placeholder="{{field.placeholder}}" />
    <div ng-show="signup_form_input.dynamic_input.$dirty && signup_form_input.dynamic_input.$invalid">
      <span class="error" ng-show="signup_form_input.dynamic_input.$error.required">The field is required.</span>
    </div>
  </div>
  <button type="submit" ng-disabled="signup_form.$invalid">Submit All</button>
</form>
</div>
Run Code Online (Sandbox Code Playgroud)

现场演示

javascript jquery angularjs

11
推荐指数
2
解决办法
2万
查看次数

错误:请在测试前调用"TestBed.compileComponents"

我收到这个错误:

错误:此测试模块使用正在使用"templateUrl"的组件MessagesComponent,但它们从未编译过.请在测试前调用"TestBed.compileComponents".

当试图运行这个简单的测试Angular 2&Jasmine Test:

  let comp:    MessagesComponent;
let fixture: ComponentFixture<MessagesComponent>;

describe('MessagesComponent', () => {
    beforeEach(() => {


        TestBed.configureTestingModule({
            declarations: [ MessagesComponent ],
            providers:    [ {provide: DataService, useValue: {} } ]

        })
            .compileComponents(); // compile template and css

        fixture = TestBed.createComponent(MessagesComponent);
        comp = fixture.componentInstance;

    });

    it('example', () => {
        expect("true").toEqual("true");
    });
});
Run Code Online (Sandbox Code Playgroud)

我想这可能是由于我的webpack测试配置的原因:

'use strict';

const path = require('path');
const webpack = require('webpack');

module.exports = {
    devtool: 'inline-source-map',
    module: {
        loaders: [
            { loader: 'raw', test: /\.(css|html)$/ },
            { exclude: …
Run Code Online (Sandbox Code Playgroud)

jasmine karma-jasmine webpack angular2-template angular

11
推荐指数
2
解决办法
7552
查看次数

使用RazorEngine和Layouts的TemplateCompilationError

我一直试图在我的一个小项目中使用RazorEngine但是当我尝试使用模板布局时无法通过这个错误.

无法编译模板.'object'不包含'Description'的定义,也没有扩展方法'Description'可以找到接受'object'类型的第一个参数(你是否缺少using指令或汇编引用?)

我的设置: 我有这样的模板布局:

<html>
<head>
    <title>@Model.Description</title>
</head>
<body>
    @RenderBody()
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

然后是一个如下所示的页面模板:

@{
    _Layout = "Layout.cshtml";
}
<h1>@Model.Description</h1>
Run Code Online (Sandbox Code Playgroud)

这是一个测试主要功能,我正在尝试解决这个问题:

    static void Main(string[] args)
    {
        // Configuration for RazorEngine
        var config = new TemplateServiceConfiguration
        {
            EncodedStringFactory = new RawStringFactory(),

            Resolver = new DelegateTemplateResolver(name =>
            {
                var file = name;
                var content = File.ReadAllText("Templates/" + file);
                return content;
            })
        };

        // Try to render output using Razor
        using (var service = new TemplateService(config))
        {
            string template = File.ReadAllText("Templates/Default.cshtml");

            dynamic model = …
Run Code Online (Sandbox Code Playgroud)

c# razor razorengine

10
推荐指数
1
解决办法
2844
查看次数

如何在更新一小部分时在视图中保留复杂对象

我觉得这可能是一个基本问题!

我有一个复杂的对象,即包含属性列表的文档对象.它是通过反序列化一些XML创建的.

我想将整个模型传递给View

Return ViewResult(MyDoc)
Run Code Online (Sandbox Code Playgroud)

在视图中编辑了一些属性.然后控制返回到后置控制器:

        [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Index(Document myDoc)
Run Code Online (Sandbox Code Playgroud)

"myDoc"现在只代表我的Form的字段.我怀疑这是ModelBinding在起作用.所以我想我需要将我的复杂对象保存在隐藏字段中(例如很棒)或者作为会话对象.但是我有点困惑我的更新字段如何合并回到持久对象(隐藏或会话).

asp.net-mvc xml-serialization asp.net-mvc-3

10
推荐指数
2
解决办法
6885
查看次数

单击foreach中的父函数绑定

我有以下html:

<div data-bind="foreach: Contacts">
   <a data-bind="click: $parent.Foo($data), text: Name">link</a>
</div>
<button data-bind="click: AddContacts">click</button>
Run Code Online (Sandbox Code Playgroud)

和js代码:

var viewModel = ko.mapping.fromJS({"Selected":null,"Contacts":[]});
viewModel.AddContacts = function(){
    this.Contacts([{"Name":"C1"},{"Name":"C2"}]);
}

viewModel.Foo = function (contact) {
    alert(contact.Name);
}

ko.applyBindings(viewModel);
Run Code Online (Sandbox Code Playgroud)

当我单击按钮时,会为每个联系人调用Foo.在点击任何链接之前,我根本没想到会调用它.

knockout.js

10
推荐指数
2
解决办法
2万
查看次数

global.asax和global.asax.cs之间有什么区别

告诉我global.asax和global.asax.cs之间的区别?

如果我在我的解决方案资源管理器中单击这两个文件,它只会转到服务器(asax.cs)方面,为什么以及如何?我可以看到客户端(global.asax)页面吗?

c# asp.net asp.net-mvc

10
推荐指数
1
解决办法
6577
查看次数

Node.js - 如何编辑jsdom窗口中的元素并将窗口另存为新的HTML文件?

我想加载一个HTML文件(使用fs.read),使用jsdom加载DOM,然后更改正文节点的文本(通过jquery).然后我想将编辑后的DOM窗口保存为HTML文件.有没有办法做到这一点?我使用的代码如下:

fs.readFile(file, 'utf8', function(error, data) {
    jsdom.env(data, [], function (errors, window) {
        var $ = require('jquery')(window);
        $(document.body.getElementsByTagName("*")).each(function () {
            var content = $(this).text();
            var word = "\\b"+wordSuggestions.word+"\\b";
            var re = new RegExp(word, "g");
            content = content.replace(re, wordSuggestions.suggestion);
            $(this).text(content);
        });

        fs.writeFile(file, data, function (error){ // saving the new HTML file? What should I put instead of data? Window?
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

html javascript jquery node.js jsdom

10
推荐指数
1
解决办法
6738
查看次数

用户授权失败:(null)

我正在使用ASP.NET MVC Core的自定义身份验证,它不使用Identity.这是Startup.cs:

public class Startup
{
    public IConfiguration Configuration { get; set; }

    // Configure IoC container
    // https://docs.asp.net/en/latest/fundamentals/dependency-injection.html
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<AppSettings>(options => Configuration.GetSection(nameof(AppSettings)).Bind(options));

        // https://docs.asp.net/en/latest/security/anti-request-forgery.html
        services.AddAntiforgery(options => options.CookieName = options.HeaderName = "X-XSRF-TOKEN");

        services.AddDbContext<DbSesamContext>(options =>
        {
            options.UseSqlServer(Configuration.GetConnectionString("SesamConnection"));
        });

        services.AddDbContext<TerminalDbContext>(options =>
        {
            options.UseSqlServer(Configuration.GetConnectionString("TerminalConnection"));
        });

        services.AddMvcCore()
            .AddAuthorization()
            .AddViews()
            .AddRazorViewEngine()
            .AddJsonFormatters();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory factory)
    {
        // Configure logging
        // https://docs.asp.net/en/latest/fundamentals/logging.html
        factory.AddConsole(Configuration.GetSection("Logging"));
        factory.AddDebug();

        // Serve static files
        // https://docs.asp.net/en/latest/fundamentals/static-files.html
        app.UseStaticFiles(); …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-core

10
推荐指数
1
解决办法
5129
查看次数

空传播运算符,输出参数和错误的编译器错误?

假设我有一个具有类型属性的类Dictionary<string,string>,可以为null.

这会编译,但调用TryGetValue()可能会NullRef在运行时抛出异常:

MyClass c = ...;
string val;
if(c.PossiblyNullDictionary.TryGetValue("someKey", out val)) {
    Console.WriteLine(val);
}
Run Code Online (Sandbox Code Playgroud)

所以我添加一个空传播运算符来防范空值,但这不会编译:

MyClass c = ...;
string val;
if( c.PossiblyNullDictionary ?. TryGetValue("someKey", out val) ?? false ) {

    Console.WriteLine(val); // use of unassigned local variable

}
Run Code Online (Sandbox Code Playgroud)

是否有一个实际的用例,valif块中未初始化,或者编译器是否只是不能推断出这个(以及为什么)?

更新:最干净的(?)解决方法^ H ^ H ^ H ^ H ^ H修复此问题:

MyClass c = ...;
string val = null; //POW! initialized.
if( c.PossiblyNullDictionary ?. TryGetValue("someKey", out val) ?? false ) { …
Run Code Online (Sandbox Code Playgroud)

c# null-propagation-operator

10
推荐指数
2
解决办法
387
查看次数